Fork splits split your code into two separate processes. Or in laymans terms we clone our program. Both the parent and child get *identical copies* of data structures and continue processing from the point immediately after the fork.
The return value is undefined if fork fails. The return value from fork for the child process is zero, and the retrun value from fork for the parent process is the process ID of the child - ie not zero. We use the returned process ID value within a script that forks to decide who we are - parent or child?.
One use is to fork off a child to do some time consuming task while allowing the parent to get on with what it was doing. Fork is the essence of parallel processing on modern Operating Systems. Active State Perl for Win32 has supported fork() at least since Build 614 I am told by crazyinsomniac.
defined(my $pid = fork) or die "Can't fork $!"; # we now have two scripts running in parallel print "I am the child\n" if $pid == 0; print "I am the parent\n" if $pid != 0; # this is another way to determine who we are if ($pid) { # do parent stuff print "Do as I say!\n"; } else { # do child stuff print "I am not deaf, I'm ignoring you!\n"; }
See this thread my children are driving me crazy!. The info is similar but I just love the title!
Here is a really silly script that demonstrates the two processes operating on completely different wavelengths ;-) If you want the parent to terminate the child process after the "You're grounded!" uncomment the kill.
$|++; # flush buffers; # set a common variable to 1, the parent will leave its # copy alone but the child will increment its copy. my $in++; defined(my $pid = fork) or die "Can't fork $!"; if ($pid) { # do parent stuff print "I am the parent!\n\n"; sleep 2; print "I am going to count to 10\n"; for (1..10) { print "$_ Do as I say!\n"; sleep $in; } print "You're grounded!\n"; # kill INT, $pid; # uncomment this to kill child process } else { # do child stuff sleep $in; print "I am the child!\n\n"; sleep $in++; print "No!\n"; sleep $in++; print "No!\n"; sleep $in++; print "No!\n"; sleep $in++; print "No!\n"; sleep $in++; print "I am not deaf, I'm ignoring you!\n"; } die "End of process \$pid = $pid \n\n";
Clarified some technical inexactitudes (marketing speak for mistakes) thanks to tye here
cheers
tachyon
s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print
In reply to Re: Forked off!
by tachyon
in thread Forked off!
by larryk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |