It makes sense to me. I'm not sure what you intended your logic to be, but it's a little confused at the moment. Try this:
if($pid > 0) { #we forked successfully $npids++; if($npids>=$MAX_PROCESSES) { my $wait=wait(); if($wait) { $npids--; } } elsif(undef $pid) { # we didn't fork successfully print "fork error!\n"; } } else { # $pid == 0, we're a kid, so what do we want to do? &doit($_); exit(0); # free this pid }
The first time through your loop, $npids is less than $MAX_PROCESSES, but $pid is defined (both in the parent and in the child), so it takes the third option. The parent (!!) goes to do_it(), sleeps for five seconds, and then exits. Oops.

I figure you probably want the children to exit. The one good way of telling the parent from the child is the value of $pid. If it's positive, you're in the parent. If it's zero, you're in a child. If it's undefined, the fork failed. (I'd move the failure code to the fork() statement.)

I can't figure out where AgentM got his comment, though. There's nothing in the newest edition of Programming Perl about wait being deprecated, and waitpid takes a different approach.


In reply to Re: For all your forking needs.. by chromatic
in thread For all your forking needs.. by reyjrar

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.