Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: making fork() a flag, and wait()ing properly

by bluto (Curate)
on Feb 08, 2002 at 16:46 UTC ( [id://144136]=note: print w/replies, xml ) Need Help??


in reply to making fork() a flag, and wait()ing properly

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://144136]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-04-24 23:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found