in reply to fork() && exit;
In the main parent process you are running the function count(), at the end of count you fork a new process (NOTE: if the value of fork returns true then you are in the parent process, a false value indicates you are in the child process) you then have "&& exit" following your fork, this results in the parent process being exited and the child process then continues on.
After the count() function is finished executing, your control is then in your child process, and you parent will have exited. So your child process then runs count2(). At the end of count2() you also "fork && exit" which results in the creation of a new child process and the exiting of the first child process. This new child is essentially the grandchild of the original process.
This grandchild process then executes the code at the bottom of your script. And as there is nothing more, it exits after that.
Seeing this visually may help explain it, so here is my (early morning/pre-coffee) attempt at it:
-> parent executes count -> count creates child <- parent exits -> child executes count2 -> count2 creates grandchild <- child exits -> grandchild executes end of script <- grandchild exits
My guess is this is not what you are after. The common code construct for use with fork is this:
I am not sure what your final intentions were in with this script, but here is a reworking of your example that will fork 3 seperate child processes from the parent and execute 3 functions then in parallel. It will also have the parent process wait for all 3 children to exit.my $PID = fork(); if ($PID) { # in the parent process } else { # in the child process }
NOTE: This is code is very untested, but from what i remember this should work right (although not without its kinks im sure).#!/usr/bin/perl $f1="file1.txt"; $f2="file2.txt"; $f3="file3.txt"; $naptime=5; sub count{ print "Starting Fork 1\n"; open(FILE1, ">$f1"); while($x < 10){ $x=$x+1; print FILE1 "$x\n"; sleep($naptime); } close(FILE1); } sub count2{ print "Starting Fork 2\n"; open(FILE2, ">$f2"); while($y < 10){ $y=$y+1; print FILE2 "$y\n"; sleep($naptime); } close(FILE2); } sub count3 { print "Starting fork 3\n"; open(FILE3, ">$f3"); while($z < 10){ $z=$z+1; print FILE3 "$z\n"; sleep($naptime); } close(FILE3); } my @funcs = (\&count, \&count2, \&count3); print "Parent Script Started!\n"; foreach my $func (@funcs) { my $PID = fork(); if ($PID) { # we are in parent wait; } else { # we are in the child so excute the function $func->(); # and exit when it is done exit; } # back in parent here,.. and we loop } print "Parent Script Finished!\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: fork() && exit;
by Abigail-II (Bishop) on Feb 23, 2004 at 17:02 UTC | |
by stvn (Monsignor) on Feb 23, 2004 at 17:09 UTC | |
|
Re: Re: fork() && exit;
by onegative (Scribe) on Feb 23, 2004 at 17:15 UTC |