so I was bugging my friend to teach me forking for a long time and he's tried a million times and I just didn't get it.. well, for this project I'm currently working on, it was necessary to fork a few processes and keep a set number of those running at any given time.. so here's a stripped down version of what I came up with based on his code and after reading over the docs for fork() and wait() a few times:

#!/usr/bin/perl use strict; my $MAX_PROCESSES=10; my $npids=0; for(1..15) { my $pid; print "Forking: $_\n"; sleep 1; $pid=fork(); 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 { #what do we want to do? &doit($_); exit(0); # free this pid } exit(0); # we shouldn't get to this point } } # if we have any stragglers, lets wait for them to finish. for(1..$npids){ my $wt=wait(); if($wt==-1){ #print "hey $!\n"; redo; } } sub doit { my $num = shift; sleep 5; print "$num DONE\n"; }

and yes, the code works just as I would expect in the production version, but in this version it does something odd that I was wondering if someone could clarify for me..
if I run the script from the command line, as the first "doit()" "exits" I get thrown back to a command prompt and the script carries on as usual in the background.. I was thinking this could be dangerous if someone accidentally managed to fork again inside that function, cause you can't just ctrl+c it to kill the program or it could spawn an infinite number of child processes you can't kill or something.. should I be using something other than exit to "end a child's life" :)

thanks..
-brad..

In reply to 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.