Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
First, inside phork(), you incorrectly try to get the parent id from within the child. Going by the Camel, 3rd ed., p. 715, the following change should be made:
elsif(defined $pid) # Quoth the Elders: # "$pid is zero here if defined" { print "Hello from in phork. " print "I am $$, and my parent is: " . getppid ."\n"; return $$; }
Secondly, you've already seen the others' comments on the problem with the children re-entering the loop and spawning their own children. Here's my take on what you can do to fix it. (I'm posting this as much to help you as to get told by others if it's a horrible idea, so caveat coder...)
use strict; $|++; my $parent_id = $$; # Before forking, save the $parent_id my $totalcounts = 0; for(my $i = 0; $i < 2; $i++) # for loop to fork 2 procs { print "[$totalcounts == $i]\n"; # just to check... # if I am the parent... if ($$ == $parent_id) { #...fork a proc and store the pid my $thispid = phork(); } # I have now forked. If I am NOT the parent... if ($$ != $parent_id) { ## Note 'if'. An else/elsif ## WON'T work here! The ## kids would skip this. #...do whatever I want to do, but when done: exit; # Now the children have been stopped # before they could continue along the $i loop. } $totalcount++; #increment the fork count }
Alternatively, add the exit() at the appropriate spot in phork().

-- Frag.


In reply to Re: Re: Re: A Quick fork theory question by frag
in thread A Quick fork theory question by E-Bitch

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 pondering the Monastery: (5)
As of 2024-04-20 00:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found