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:
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...)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 $$; }
Alternatively, add the exit() at the appropriate spot in phork().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 }
-- Frag.
|
---|
In Section
Seekers of Perl Wisdom