# Include < Signal. h >
# Include < Stdio. h >
# Include < Setjmp. h >
/**/ /*
* Signal function use sigaction
**/
Typedef Void Sigfunc ( Int Signo );
Static Jmp_buf env_alarm;
Sigfunc * Signal1 ( Int Signo, sigfunc * Func)
{
Struct Sigaction act, oact;
Act. sa_handler = Func;
Sigemptyset ( & Act. sa_mask );
Act. sa_flags = 0 ;
If (Signo = Sigalrm) // Timer
{
# Ifdef sa_interrupt
Act. sa_flags| =Sa_interrupt;
# Endif
}
Else
{
# Ifdef sa_restart
Act. sa_flags| =Sa_restart;
# Endif
}
If (Sigaction (signo, & Act, & Oact) < 0 )
Return (Sig_err );
Return (Oact. sa_handler );
}
Void Sig_proc ( Int Signo)
{
//Timeout then return
Longjmp (env_alarm,10);//10 means return value is 10;
}
Int Main ()
{
Int I = 1 ;
Int Jmpret;
If (Signal1 (sigalrm, sig_proc) = Sig_err)
{
Printf ("Signal sigalrm error \ n");
Return -1;
}
If (Jmpret = Setjmp (env_alarm )) ! = 0 ) // Longjmp return
{
Printf ("Time out! Return % d. \ n", Jmpret );//Here will print return 10.
Return 0;
}
Alarm ( 2 ); // Set timeer 2 second, and then call the sig_proc
While (I)
{< br> If (I % 3 = 0 )
printf ( " the value is: % d \ n " , I );
I ++ ;< BR >}
Alarm ( 0 );
Return 0 ;
}
Use sigaction to implement the signal function, and then use an example to test it.
In this example, print a multiple of 3 and receive the sigalrm signal after two seconds of operation.