In Perl, is there a way to be notified that a PID has died, when the PID is not the…
- User
In Perl, is there a way to be notified that a PID has died, when the PID is not the child of our process, and without shelling out to ps or something?
- Assistant
Yes, you can use the
POSIXmodule to catch theSIGCHLDsignal, which is sent to a process when one of its child processes terminates. Here's an example:codeuse POSIX qw(:signal); # set up signal handler $SIG{CHLD} = sub { my $pid = wait(); print "PID $pid has died\n"; }; # start a subprocess my $pid = fork(); if ($pid == 0) { # run child process exit(0); } # do other stuff while waiting for child while (1) { # do something else }In this example, we set up a signal handler for
SIGCHLDthat waits for a child process to terminate and then prints a message indicating which PID has died. We then fork a child process and do other stuff in the parent while waiting for the child to terminate. When the child terminates, the signal handler is called and the message is printed.Note that this only works if the process you want to monitor is a child process of your own process. If it's not, you may need to use a different approach such as polling the process table periodically or using a system-level monitoring tool.