sonalig has asked for the wisdom of the Perl Monks concerning the following question:

Hello All, I am forking a process in a for loop using exec and in the parent process, I want to kill the child processes. How can I get to know the pids for each of the child processes that were created? In the parent process, I can get to know the pid for one child using pid, but what about the rest? here's my psuedo code:
for loop { $pid=fork; exec (command); } if ($pid > 0) { # I am in the parent process kill child pid; # How to do for multiple child processes? }
I can use the modules or can do ps -ef > file and parse the file to getthe child pids and kill them. I don't want to use modules. Is there some other way of doing the above? Thanks

Replies are listed 'Best First'.
Re: how to get pid for multiple child process in parent process
by pc88mxer (Vicar) on Jul 01, 2008 at 00:05 UTC
    Just save the pids as you generate them:
    my @pids; for loop { $pid = fork(); if ($pid) { # if parent push(@pids, $pid); } else { # if child ... exit; } } # only parent reaches this point kill 9, @pids; # perform mass filicide
    or... have waitpid() tell you what they are:
    use POSIX qw(:syswait_h); while ((my $pid = waitpid(-1, WNOHANG)) != -1) { kill 9, $pid; }
Re: how to get pid for multiple child process in parent process
by Fletch (Bishop) on Jul 01, 2008 at 00:06 UTC

    Erm, is there some problem with declaring an array outside of the for loop and storing them there as fork returns them that you've already encountered and that's why you've already dismissed the obvious solution?

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: how to get pid for multiple child process in parent process
by thezip (Vicar) on Jul 01, 2008 at 00:11 UTC

    You could always do something like:

    my $result = qx/pgrep .*/;

    This would result in a set of pids for the active shell, one per line. You'll have to investigate to determine the usability of these results. Also, I have only shown the broadest possible result... you'll be able to tweak the arguments to pgrep to fine-tune it.

    Here's the current output on my system:

    foo@bar ~: pgrep .* 64667 64666 64663 63664 63554 63227 93711 92292 76330 74514 57312 18496 64105 5883 5882 5881 9224 630 623 565

    I hope this is helpful.


    Your wish is my commandline.