I don't think there's anything wrong with polling with waitpid, but I wonder if it can be avoided somehow. Perhaps you could create children with "open my $child_fh, '-|'" and have the parent use IO::Select to wait on them. The child does a fork,exec and a blocking wait (or just system), and it writes a status line back to the parent before it exits.

You may want to store a start time for each process and give it a time limit in case something hangs one day.

Looking at what you have, it seems as if it could be simpler. I haven't tested this, but it's how I'd start...

my $children_wanted = 6; my @job_queue = map { 'sleep ' . int rand 100 } 1 .. 140; my %job_of = (); while ( $children_wanted < scalar keys %job_of && @job_queue ) { my $job = go( shift @job_queue ); $job_of{ $job->{pid} } = $job; wait_on_jobs(); sleep 5; } wait_on_jobs() while %job_of; my $too_long = whatever(); sub wait_on_jobs { foreach my $job ( values %job_of ) { my $pid = $job->{pid}; if ( $pid == waitpid $pid, WNOHANG ) { delete $job_of{ $pid }; } if ( time() - $job->{start} > $too_long ) { kill 'TERM', $pid; } } return; } sub go { my ( $cmd ) = @_; my $pid = fork; if ( ! defined $pid ) { die "Can't fork: $!"; } if ( $pid ) { # parent return { pid => $pid, cmd => $cmd, start => time() }; } else { # child # close and exec and stuff } die 'unreachable code reached'; }

In reply to Re: Using perl to manage child processes - critique my code. by kyle
in thread Using perl to manage child processes - critique my code. by FatDog

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.