in reply to fork - child executes code outside of block

#!/bin/perl -w my $pid = fork(); if ($pid) { print "PARENT --" . "\n"; waitpid(-1, 0) ; print "-- PARENT " . "\n"; } elsif ( $pid == 0 ) { print "CHILD --" . "\n"; exit; } print "PID - $pid , MAIN PRG --" . "\n";

Replies are listed 'Best First'.
Re^2: fork - child executes code outside of block
by ikegami (Patriarch) on Mar 28, 2018 at 18:47 UTC

    Why split the parent's code like that?

    defined( my $pid = fork() ) or die("fork: $!"); if (!$pid) { print "CHILD --" . "\n"; exit; } print "PARENT --" . "\n"; waitpid($pid, 0) ; print "-- PARENT " . "\n"; print "PID - $pid , MAIN PRG --" . "\n";

      I just made the minimum change to fix the problem.

      It's not my favorite way of doing fork, which is:

      if( my $pid = fork ) { # parent } elsif( defined $pid ) { # child exit; } else { die "$! on fork"; }

        The question wasn't necessarily directed at you originally, but you showed that it applies to you too. Why do you arbitrarily split the parent code in three (partly before the if, partly in the if, partly after the if)? And why do you hide the error handling code far from where the error code occurred?