http://qs1969.pair.com?node_id=88600


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

Maybe I wasnt as informed as I thought... I am trying to run the following code:
#!/usr/bin/perl -w $|++; print "Hello before fork\n"; #print first message $thiscount = 0; #counter for number of forks for($i = 0; $i < 2; $i++) #for loop to fork 2 procs { $thispid = phork(); #fork a proc, store the pid print "Just forked $thispid\n"; #tell us what you've done $thiscount++; #increment the fork count } $wpid = wait; #wait until children are finished print "i'm waiting on $wpid\n"; #tell us what you've done print "hello from after fork. I have forked $thiscount child processe +s.\n"; #final message from parent? sub phork() #subroutine for forking stuff { $cid = 0; #child id $count = 0; #number of times through. FORK: { print "i am about to start forking stuff. my id is $$, and i +have done this $count times\n"; $count++; #increment the number of times through if($pid = fork()) #parent process { print "Parent phorking child. I am: $$, and my child is $ +pid\n"; $cid = $pid; } elsif(defined $pid) #child processs { print "Hello from in phork. I am $$, and my parent is: $p +id\n"; return $$; } elsif($! =~ /No more process/) #error { sleep 5; redo FORK; } else #error { die "Cant phork: $!\n"; } } return $cid; #ship back the child id }
my intentions are to fork 2 children, have them print out their process IDs, and return to the main part of the program, and then the main portion waits on the children to finish, then prints out that it too is finished. I get the following results.:
[33] rk110759@sunray22: test.pl Hello before fork i am about to start forking stuff. my id is 15092, and i have done th +is 0 times Parent phorking child. I am: 15092, and my child is 15095 Just forked 15095 i am about to start forking stuff. my id is 15092, and i have done th +is 0 times Parent phorking child. I am: 15092, and my child is 15096 Just forked 15096 Hello from in phork. I am 15096, and my parent is: 0 Just forked 15096 Hello from in phork. I am 15095, and my parent is: 0 Just forked 15095 i am about to start forking stuff. my id is 15095, and i have done th +is 0 times i'm waiting on -1 hello from after fork. I have forked 2 child processes. Parent phorking child. I am: 15095, and my child is 15097 Just forked 15097 Hello from in phork. I am 15097, and my parent is: 0 Just forked 15097 i'm waiting on -1 hello from after fork. I have forked 2 child processes. i'm waiting on 15097 hello from after fork. I have forked 2 child processes. i'm waiting on 15095 hello from after fork. I have forked 2 child processes.
Am i being ignorant, and my program is actually printing out what it I intended? and why does the message after the fork ("hello from after fork...") get printed out 4 times?