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__
In reply to Re: Confused by fork examples
by ambrus
in thread Confused by fork examples
by webshark
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |