Blocking Signals
Now and then, you’d like to delay receipt of a signal during some critical
section of code. You don’t want to blindly ignore the signal, but what
you’re doing is too important to interrupt. Perl’s %SIG hash doesn’t implement signal blocking,
but the POSIX module does, through its interface to the
sigprocmask(2) syscall:
use POSIX qw(:signal_h);
$sigset = POSIX::SigSet–>new;
$blockset = POSIX::SigSet–>new(SIGINT, SIGQUIT, SIGCHLD);
sigprocmask(SIG_BLOCK, $blockset, $sigset)
|| die "Could not block INT,QUIT,CHLD signals: $!\n";Once the three signals are all blocked, you can do whatever you want without fear of being bothered. When you’re done with your critical section, unblock the signals by restoring the old signal mask:
sigprocmask(SIG_SETMASK, $sigset)
|| die "Could not restore INT,QUIT,CHLD signals: $!\n";If any of the three signals came in while blocked, they are
delivered immediately. If two or more different signals are pending, the
order of delivery is not defined. Additionally, no distinction is made
between having received a particular signal once while blocked and
having received it many times.[157] For example, if nine child processes exited while you were
blocking CHLD signals, your handler
(if you had one) would still be called only once after you unblocked.
That’s why, when you reap zombies, you should always loop until they’re
all gone.
[157] Traditionally, that is. Countable signals may be implemented on some real-time systems according to the latest ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access