in reply to Confused by fork examples

Beware, I think this code you gave is wrong:

$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 }
If fork gives an error, it will execute the first body; the third body is never executed.

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
    ambrus,
    To quote the docs: It returns the child pid to the parent process, 0 to the child process, or undef if the fork is unsuccessful.

    I believe the 3rd block would be executed if fork failed because it would return undef not 0?

    Update: Specifically, I am referring to your comment If fork gives an error, it will execute the first body; the third body is never executed. I now see your point. If the $pid is undef then ($pid == 0) won't work as intended. Thanks.

    Cheers - L~R

      In the CB, you were looking for documentation that I know I had seen in the past. mr_mischief jogged my memory as to where it was.

      • pink camel, under fork() (page 146)
      • blue camel, under fork() (page 167)

      hth

      --MidLifeXis

        For those with the Perl CD Bookshelf (which has no page numbers for the electronic-only versions) the 3rd Edition of the Camel has what I think we're talking about in section 29.2.40 (Chapter 29, section 2: Perl Functions in Alphabetical Order).