Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-24 20:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found