On 4/17/06, Henry, Mark Patrick <[EMAIL PROTECTED]> wrote:
snip
> Seems like what I want is something along the lines of fork /
> child_pids, and 'wait'.
snip

Yep, that is what you want.

snip
> If I launch multiple jobs up to max_machines as it were, and use 'wait',
> it appears to only wait for one job - the first - and then the others
> are on their own.  (e.g. the 'post-wait' print below is hit after the
> first pid ends).
> And if I 'waitpid', it serializes the jobs, defeating the parallelism I
> so need!
snip

This is one form of the code you want (there are others depending on
what exactly you want to do).  I would suggest you read the perlipc
page for more information.  You can do this by typing "perldoc
perlipc" or going to

http://perldoc.perl.org/perlipc.html

#!/usr/bin/perl -w

use strict;
use POSIX ":sys_wait_h";

my %pids;

print "$$:starting parent\n";
for my $val ( 20, 25, 30 ) {
        print "$$:value is $val\n";
        my $pid = fork;
        die "$$:cannot fork: $!" unless defined $pid;
        if ($pid) {
                # I'm the parent
                $pids{$pid} = $val;
        } else {
                # I'm the child
                print "$$:sleeping for $val seconds.\n";
                sleep $val;
                print "$$:$val is done sleeping, exiting.\n";
                exit;
        }
}
print "$$:outside of loop.\n";
while (keys %pids) {
        while ((my $pid = waitpid(-1, WNOHANG)) > 0) {
                print "$$:saw exit of $pid (who was asleep $pids{$pid}s)\n";
                delete $pids{$pid};
        }
        sleep 1;
}
print "$$:all children are finished\n";

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to