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

Re: Re: Re: A Quick fork theory question

by frag (Hermit)
on Jun 15, 2001 at 01:48 UTC ( #88639=note: print w/replies, xml ) Need Help??

in reply to Re: Re: A Quick fork theory question
in thread A Quick fork theory question

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. 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.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2022-05-19 14:52 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (71 votes). Check out past polls.