A minor nit: your declaration of pid should probably just be
my $pid;
... since I'm not sure what the 'if' buys you.

While you can do what you'd like with your code, I'd personally move the child code into a separate subroutine and then have a big 'if ($fork)' at the beginning that called it in the fork loop and in the else clause, in order to keep the forking code as easy to read as possible -- YMMV.

Other than that, your code looks ok up until the wait() (i.e. you do need an explicit exit in the child code). You'll probably want to do your waiting outside of the forking loop, in a loop of it's own. You'll want to call wait() one time for each time you fork. Something like...

while ($childcnt > 0) { wait(); $childcnt--; }
Of course you'll need to keep track of the number of children running by incrementing $childcnt each time you perform a fork in the parent code (i.e. right before the 'next' line).

FWIW, in your code if the fork fails you 'die' right away. I'd probably just report an error, drop out of the loop, wait for all of the children to die, and then die. Otherwise, your existing children will continue to run without a parent (perhaps you want it to do this?).

bluto


In reply to Re: making fork() a flag, and wait()ing properly by bluto
in thread making fork() a flag, and wait()ing properly by c

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.