http://qs321.pair.com?node_id=298641


in reply to Killing child process

To quote the perlfunc manpage for kill,
Unlike in the shell, if SIGNAL is negative, it kills process groups instead of processes. (On System V, a negative PROCESS number will also kill process groups, but that's not portable.) That means you usually want to use positive not negative signals.
So all you have to do is call kill with the negative value for the signal you want. E.g. kill -9, $pid;. If you want to use the name of a signal, I think you'll have to do something like:
use POSIX; kill - SIGKILL, $pid;
(If you leave out the space after the minus sign, you'll get a warning message like "Ambiguous use of -SIGKILL resolved as -&SIGKILL()". Of course you could type  kill -&SIGKILL(), $pid, but it seems easier to just leave a space).

Replies are listed 'Best First'.
Re: Re: Killing child process
by sgifford (Prior) on Oct 12, 2003 at 15:49 UTC
    I couldn't get that to work:
    #!/usr/bin/perl -w use strict; $SIG{TERM}= sub { print "TERM $$\n"; exit(1); }; if (my $kidpid = fork) { # Parent sleep(1); print "\n"; kill -15, $kidpid; sleep(5); } else { print "CREATED CHILD $$\n"; # Child for my $i (1..10) { if (!fork) { # Grandchild print "CREATED GRANDCHILD $$\n"; sleep(5); exit(0); } } sleep(300); }
    Is there a bug in this code, or are things not working as documented?
      Oops, yeah, I forgot you need to set the process group for the process you want to be a group leader. To do this call setpgrp(0,0); after the fork. In your test program, do it right where you have print "CREATED CHILD $$\n"; and don't do it in the grandchildren.

        Cool, that worked! Thanks, I've always wondered how process groups worked.

        Now, I wonder if this answered the OP's question?... :-)

      Two points about OS:
      • To send a signal to a process group, you have to be a super user;
      • Most of OS's, if not all, does not let you capture SIGTERM for ordinary users. That's for a good reason, if some processes (intentionally or by mistake - bugs) decide to be alive forever, that will really be a nightmare.
          • This program doesn't work when run as root either.
          • I believe you're thinking of SIGKILL. SIGTERM is a perfectly normal signal. If I change the kill command to just send a normal signal to $kidpid, then the child process prints the TERM message, but not the grandchildren. Similarly, if you make the sleeps a little longer, you can send TERM signals by hand to individual grandchildren, and they print the message.