cyadav has asked for the wisdom of the Perl Monks concerning the following question:

Here's the code

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

Child is able to execute this line of code  print "PID - $pid , MAIN PRG --" . "\n"; - that it shouldn't be.

Here's the output -

PARENT -- CHILD -- PID - 0 , MAIN PRG -- -- PARENT PID - 53784 , MAIN PRG --
Can you please explain ? Is something wrong here ? how to solve this ?

Replies are listed 'Best First'.
Re: fork - child executes code outside of block
by hippo (Archbishop) on Mar 28, 2018 at 14:13 UTC

    Your assertion (assumption?) that the child should not be able to execute that print line is false. Why should it not when it is outside the entire "if" block?

      Ah! thanks :)

Re: fork - child executes code outside of block
by tybalt89 (Monsignor) on Mar 28, 2018 at 14:17 UTC
    #!/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";

      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"; }