Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: fork - child executes code outside of block

by tybalt89 (Monsignor)
on Mar 28, 2018 at 14:17 UTC ( [id://1211917]=note: print w/replies, xml ) Need Help??


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?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1211917]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-03-29 08:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found