I'm on Linux platform and using Perl. First of all I created a thread, and forked a child process in this new thread. When the parent in the new thread returned and joined to the main thread, I would like to send TERM signal to the child process spawned in the created thread, but the signal handler doesn't work, and the child process becomes zombie. Here's my code:
use strict;
use warnings;
use Thread 'async';
use POSIX;
my $thrd = async {
my $pid = fork();
if ($pid == 0) {
$SIG{TERM} = \&child_exit;
`echo $$ > 1`;
for (1..5) {
print "in child process: cycle $_\n";
sleep 2;
}
exit(0);
}
else {
$SIG{CHLD} = \&reaper;
}
};
$thrd->detach();
sleep 4;
my $cpid = `cat 1`;
kill "TERM", $cpid;
while (1) {}
sub child_exit {
print "child $$ exits!\n";
exit(0);
}
sub reaper {
my $pid;
while (($pid = waitpid(-1, &WNOHANG)) > 0) {
print "reaping child process $pid\n";
}
}
Any suggestions about how to successfully and safely send signal in this situation?