The Linux Programming Interface

(nextflipdebug5) #1
Signals: Advanced Features 469

An example of the use of sigwaitinfo() is shown in Listing 22-6. This program
first blocks all signals, then delays for the number of seconds specified in its
optional command-line argument. This allows signals to be sent to the program
before sigwaitinfo(). The program then loops continuously using sigwaitinfo() to
accept incoming signals, until SIGINT or SIGTERM is received.
The following shell session log demonstrates the use of the program in
Listing 22-6. We run the program in the background, specifying that it should
delay 60 seconds before calling sigwaitinfo(), and then send it two signals:


$ ./t_sigwaitinfo 60 &
./t_sigwaitinfo: PID is 3837
./t_sigwaitinfo: signals blocked
./t_sigwaitinfo: about to delay 60 seconds
[1] 3837
$ ./t_sigqueue 3837 43 100 Send signal 43
./t_sigqueue: PID is 3839, UID is 1000
$ ./t_sigqueue 3837 42 200 Send signal 42
./t_sigqueue: PID is 3840, UID is 1000

Eventually, the program completes its sleep interval, and the sigwaitinfo() loop
accepts the queued signals. (We see a shell prompt mixed with the next line of the
program’s output because the t_sigwaitinfo program is writing output from the
background.) As with realtime signals caught with a handler, we see that signals are
delivered lowest number first, and that the siginfo_t structure passed to the signal
handler allows us to obtain the process ID and user ID of the sending process:


$ ./t_sigwaitinfo: finished delay
got signal: 42
si_signo=42, si_code=-1 (SI_QUEUE), si_value=200
si_pid=3840, si_uid=1000
got signal: 43
si_signo=43, si_code=-1 (SI_QUEUE), si_value=100
si_pid=3839, si_uid=1000

We continue, using the shell kill command to send a signal to the process. This
time, we see that the si_code field is set to SI_USER (instead of SI_QUEUE):


Press Enter to see next shell prompt
$ echo $$ Display PID of shell
3744
$ kill -USR1 3837 Shell sends SIGUSR1 using kill()
$ got signal: 10 Delivery of SIGUSR1
si_signo=10, si_code=0 (SI_USER), si_value=100
si_pid=3744, si_uid=1000 3744 is PID of shell
Press Enter to see next shell prompt
$ kill %1 Terminate program with SIGTERM
$
Press Enter to see notification of background job termination
[1]+ Done ./t_sigwaitinfo 60
Free download pdf