If no signal in set is pending at the time of the call, the thread shall be suspended until one or more becomes pending. The signals defined by set shall have been blocked at the time of the call to sigwait(); otherwise, the behavior is undefined. The effect of sigwait() on the signal actions for the signals in set is unspecified.
This is really ambiguous ,what's the difference between pending
and block
here?
And its conclusion on how to choose between sigwait
and sigaction
is not clear at all:
In summary, when it is necessary for code run in response to an asynchronous signal to notify a thread, sigwait() should be used to handle the signal. Alterna- tively, if the implementation provides semaphores, they also can be used, either following sigwait() or from within a signal handling routine previously registered with sigaction().
Can someone make the reason of sigwait
more rational?
From the
signal(7)
man page:"Pending" and "blocked" are not mutually exclusive.
Also from the
signal(7)
man page:So
sigaction()
is used to allow other code to run until a signal is pending, whereassigwait()
suspends execution of the thread until a signal is pending but blocked.Every process has what's called a signal mask associated with it, which defines the set of signals which are blocked. The signal mask can be queried or set with
setprocmask(2)
(for single-threaded code) andpthread_sigmask(3)
(for multithreaded code).Whenever a signal is raised (either explicitly via
kill(2)
orraise(3)
, or via some other mechanism such as a segmentation fault raisingSIGSEGV
), the signal is checked against the current signal mask. If the signal is not blocked, then it is acted upon immediately: the corresponding signal handler is called if set, otherwise the default action (typically exiting with abnormal status or ignoring it) is run. If the signal is blocked by the signal mask, then the state of the signal is set to pending, and the program continues execution.So consider the following example program:
Output: