# 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 ).