in reply to Confused by fork examples
Beware, I think this code you gave is wrong:
If fork gives an error, it will execute the first body; the third body is never executed.$pid=fork; if ($pid==0) {try and start new process with exec??} elsif ($pid) {do what I want to do with this script??} else {die because of fork error }
The correct way is to use the defined function to test for an error, something like this:
use warnings; $pid = fork; if (!defined($pid)) { die "fork error"; } elsif (!$pid) { #line 6 "child" warn "starting"; for (1 .. 5) { sleep 1; warn "working hard. really. ", $_*20, "%"; } exit; # or exec } else { #line 14 "parent" warn "starting the parent"; for (1 .. 2) { sleep 1; warn "doing some work"; } warn "waiting for the child to finish (or just collecting it if it + has finished"; $pid == waitpid($pid, 0) or die "error waiting: $!"; 0 == $? or die "child has died"; warn "ok, collected the child successfully"; } __END__
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Confused by fork examples
by Limbic~Region (Chancellor) on Feb 20, 2009 at 17:58 UTC | |
by MidLifeXis (Monsignor) on Feb 20, 2009 at 18:20 UTC | |
by mr_mischief (Monsignor) on Feb 20, 2009 at 18:35 UTC |