# Custom Signal Functions

Source: Internet
Author: User
# 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.

Related Keywords:

### Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.