I have a test-case where multiple fork is used to create grandchild and the parent process is in infinite loop, I am implementing a perl script to kill the process. Currently it
In a more complicated case, you can set the perl child process to be a session leader with POSIX::setsid()
, and then send the signal to the process group by passing a negative value to kill
.
if(!defined( my $pid = fork())) {
die "Cannot fork a child: $!";
} elsif ($pid == 0) {
POSIX::setsid(); # make this process a session leader
print "Printed by child process\n";
system("./program_that_forks"); exit; # or exec('./program_that_forks')
} else {
...
kill('KILL', -$pid); # -$pid means signal the whole process group
...
}
If the program_that_forks
is also manipulating process groups, either by calling setsid(1)
or by closing standard file descriptors and becoming a daemon, the convention is for the program to write its process id to a file, and for system task scripts to read this file to signal the program (run ls /var/run/*.pid
to see some examples).