in reply to How do you get PID of a program called using system call?

Here is an example to get you started:
#!/usr/bin/perl -wT use strict; %ENV = (); # clean out the %ENV hash to prevent mischief $ENV{PATH} = '/bin'; my @pids; # array for storing childr +ens pids my $cmd = 'sleep 2; echo "I am child $$"'; # command children will ex +ecute for (1..4) { my $childpid = fork() or exec($cmd); # fork off a child push(@pids,$childpid); # store the childs pid in @pid +s } print "My Children: ", join(' ',@pids), "\n"; waitpid($_,0) for @pids; # wait for children to finish print "Children are done\n";

-Blake

Replies are listed 'Best First'.
Re: Re: How do you get PID of a program called using system call?
by gbarr (Monk) on Oct 08, 2001 at 17:22 UTC
    You should really check the return values from fork() and exec() or you can get yourself into a lot of mess.

    If fork() was not able to fork, it will return undef and if exec() is not able to run the program it will return.

    my $pid = fork(); if ($pid) { push @pids, $pid; } elsif (defined $pid) { exec($cmd); die "Cannot exec '$cmd': $!\n"; } else { die "Cannot fork: $!\n" }
    Not catching the exec is potentially the most dangerous as the child process then continues in the loop, just the same as the parent. In this cas you would end up filling the process table.
      Good point. I certainly should have checked the return values. There is a large potential bug lying in wait there.

      I don't think this would ever fill up the proc table though, The loop is bound by a for (1..4) which means that in the wost case, we would have:

      1 parent through the first time (creates 1 child) 1 parent 1 child the second time (creates 2 children) 2 parents 2 children the third time (creates 4 children) 4 parents 4 children the fourth time (creates 8 children)
      So at most I see a possible 16 procs being active at once.... of course they might never exit due to the messed up @pids array, but thats another matter.

      Again, thanks for the catch.

      -Blake