Reaping Zombies
When a process exits, its parent is sent a CHLD signal by the kernel, and the process
becomes a zombie[156] until the parent calls wait or waitpid. If you start another process in Perl
using anything except fork,
Perl takes care of reaping your zombied children; but if you
use a raw fork, you’re expected to
clean up after yourself. On many but not all kernels, a simple hack for
autoreaping zombies is to set $SIG{CHLD} to "IGNORE". A more flexible (but tedious)
approach is to reap them yourself. Because more than one child may have
died before you get around to dealing with them, you must gather your
zombies in a loop until there aren’t any more:
use POSIX ":sys_wait_h";
sub REAPER { 1 until waitpid(–1, WNOHANG) == –1 }To run this code as needed, you can either set a CHLD signal handler for it:
$SIG{CHLD} = \&REAPER;or, if you’re running in a loop, just arrange to call the reaper every so often.
[156] Yes, that really is the technical term.
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