Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 10.14 sigactionFunction 349


The process blocksSIGQUIT,saving its current signal mask (to restorelater), and then
goes to sleep for 5 seconds. Any occurrence of the quit signal during this period is
blocked and won’t be delivered until the signal is unblocked. At the end of the
5-second sleep, we check whether the signal is pending and unblock the signal.
Note that we saved the old mask when we blocked the signal. To unblock the
signal, we did aSIG_SETMASKof the old mask. Alternatively, we couldSIG_UNBLOCK
only the signal that we had blocked. Be aware, however, if we write a function that can
be called by others and if we need to block a signal in our function, we can’t use
SIG_UNBLOCKto unblock the signal. In this case, we have to useSIG_SETMASKand
restorethe signal mask to its prior value, because it’s possible that the caller had
specifically blocked this signal beforecalling our function. We’ll see an example of this
in thesystemfunction in Section 10.18.
If we generate the quit signal during this sleep period, the signal is now pending
and unblocked, so it is delivered beforesigprocmaskreturns. We’ll see this occur
because theprintfin the signal handler is output beforetheprintfthat follows the
call tosigprocmask.
The process then goes to sleep for another 5 seconds. If we generate the quit signal
during this sleep period, the signal should terminate the process, since we reset the
handling of the signal to its default when we caught it. In the following output, the
terminal printsˆ\when we input Control-backslash, the terminal quit character:
$./a.out
ˆ\ generate signal once (before5seconds areup)
SIGQUIT pending after return fromsleep
caught SIGQUIT in signal handler
SIGQUIT unblocked after return fromsigprocmask
ˆ\Quit(coredump) generate signal again
$./a.out
ˆ\ˆ\ˆ\ˆ\ˆ\ˆ\ˆ\ˆ\ˆ\ˆ\ generate signal 10 times (before5seconds areup)
SIGQUIT pending
caught SIGQUIT signal is generated only once
SIGQUIT unblocked
ˆ\Quit(coredump) generate signal again
The messageQuit(coredump)is printed by the shell when it sees that its child
terminated abnormally.Note that when we run the program the second time, we
generate the quit signal ten times while the process is asleep, yet the signal is delivered
only once to the process when it’s unblocked. This demonstrates that signals arenot
queued on this system.

10.14 sigactionFunction


Thesigactionfunction allows us to examine or modify (or both) the action associated
with a particular signal. This function supersedes thesignalfunction from earlier
releases of the UNIX System. Indeed, at the end of this section, we show an
implementation ofsignalusingsigaction.
Free download pdf