in reply to Forking and waiting

Check out the waitpid and wait functions in perlfunc.

Replies are listed 'Best First'.
RE: Re: Forking and waiting
by Silas (Novice) on May 29, 2000 at 07:58 UTC
    Right, I should have mentioned that I looked at both of those, too.

    I just tried this variation with some success:

    my ($i, $return, $pid, @pids);
    for ($i = 1; $i <= 3; $i++) {
      if ($pid=fork) {
        push @pids, $pid;
      } elsif (defined $pid) {
        $return = &my_function($i);
        print "Returned: $return\n";
        exit;
      }
    }
    
    foreach my $childpid (@pids) {
      waitpid($childpid, 0);
    }
    
    print "All is done!\n";
    
    Does that seem a reasonable/efficient way to handle this?

    Thanks.

      just wait for the CHILD in the parent:

      my ($i, $return, $pid, @pids); for ($i = 1; $i <= 3; $i++) { if ($pid=fork) { push @pids, $pid; waitpid($pid,0); } elsif (defined $pid) { $return = &my_function($i); print "Returned: $return\n"; exit; } } print "All done.\n";
        ++
        Thanks slayven for waitpid($pid,0);

      Y'know, for ($i = 1; $i <= 3; $i++) {} is a horribly un-Perlish way to write for (1..3) {}

        You'll note that I use the $i variable further down in the code.
        i thought it was easier to drop the waitpid-statement into his code
        instead of explaining where he has to put it into :)