Simple Program for capturing SIGUSR1 and sigusr2

Source: Internet
Author: User
Tags signal handler
# Include <stdio. h> 
# Include <signal. h>
# Include <unistd. h>

Static Void Sig_usr ( Int );
Int Main ( Void )
{
If(Signal (SIGUSR1, sig_usr) = sig_err)
Printf ( "Can't catch SIGUSR1 \ N " );
If(Signal (sigusr2, sig_usr) = sig_err)
Printf ( "Can't catch sigusr2 \ N " );
For(;;)
Pause ();
}

Static Void Sig_usr ( Int Signo)
{
If(Signo = SIGUSR1)
Printf ( "Received SIGUSR1 \ N " );
Else If(Signo = sigusr2)
Printf ( "Received sigusr2 \ N " );
Else
Printf ( "Received Signal % d \ N " , Signo );
}

The running result is:
[Chinstrap @ ThinkPad apue] $./A. Out &
[1] 2581
[Chinstrap @ ThinkPad apue] $ kill-usr1 2581
Received SIGUSR1
[Chinstrap @ ThinkPad apue] $ kill-usr2 2581
Received sigusr2
[Chinstrap @ ThinkPad apue] $ kill 2581
[1] + terminated./A. Out

Note:
Void sig_usr (INT) is the signal handler function used to register signals. Its implementation only prints the received signals. It is special for SIGUSR1 and sigusr2 signals, print the signal name directly.

In the main function, two signals are registered: SIGUSR1 and sigusr2, and then an endless loop. The pause continuously receives signals without exiting the corresponding mechanism of the loop, only the kill command can be used to end the process.

So now, this smallProgramIt is easy to understand. The program first registers SIGUSR1 and sigusr2 signals to the sig_usr signal processing function, and the signal processing function sig_usr processes the signals as follows: if the signal is SIGUSR1 or sigusr2, print the signal type. Otherwise, print the signal value.

Inadvertently, we have implemented an inter-process communication: the process that executes the kill command transmits the SIGUSR1 or sigusr2 signal to the process with the process ID 2581, and after the process 2581 receives the signal, according to the conventions (registered signal processing functions), the corresponding processing (print process information) is performed ).

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.