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

Hi All, I am testing the fork feature in the Linux. In below code out of 3 child parent randomly check one child and wait for it to finish and moves to another. I was wondering is it possible to make parent to report the child which finish first and another child that finish second and the third?

use strict; use warnings; use POSIX ":sys_wait_h"; handler(); sub handler { my %process = ( A => 'sleep 10 && exit 0', B => 'sleep 15 && exit 0', C => 'sleep 25 && exit 1', ); my @child_pids; foreach my $process(keys %process) { my $pid = fork; if($pid) { #Parent. # print "Launched $process | $pid\n"; push(@child_pids, {PID => $pid, PROCES +S => $process{$process}}); } elsif($pid == 0) { exec $process{$process}; die "Can't exec $process"; } else { #Parent # Fork failed. die "cant fork $!\n"; } } foreach my $href (@child_pids) { print "Waiting $href->{PID} | $href->{ +PROCESS}\n"; while (waitpid($href->{PID}, WNOHANG) +== 0) { sleep 1; } print "Failed $href->{PROCESS}\n" unle +ss($? == 0); print "Done $href->{PID} | $href->{PRO +CESS}\n"; } }

Replies are listed 'Best First'.
Re: fork report child finish by order child process finish.
by aitap (Curate) on Sep 10, 2012 at 09:20 UTC

    Unless you are training yourself, it should be easier to use Parallel::ForkManager and its run_on_finish callback.

    Manual way to do this is sequentially running waitpid with WHOHANG flag and checking its return value for all pids running. Example (untested):

    foreach my $process (@child_pids) { if (waitpid($process->{PID}, WNOHANG)) { print "Process $process->{PROCESS} terminated\n"; } }

    Sorry if my advice was wrong.
Re: fork report child finish by order child process finish.
by locked_user sundialsvc4 (Abbot) on Sep 10, 2012 at 16:55 UTC

    You are describing a Workflow management system ... the hard way.

    If the business situation is that “report #4 cannot start until reports #1 and #3 have finished,” and you find yourself writing custom Perl programs to shepherd that ... then you are “doing a thing that has already been done.”

Re: fork report child finish by order child process finish.
by tart (Beadle) on Sep 11, 2012 at 02:41 UTC
    Thanks aitap! Your advice definitely helped me to move further. Cheers!