Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Fork() Function

by McA (Curate)
on May 13, 2014 at 13:51 UTC ( #1085903=note: print w/ replies, xml ) Need Help??


in reply to Fork() Function

Hi,

the following code is directly taken from the perldoc perlipc which should give an idea about the bookkeeping:

use POSIX ":sys_wait_h"; # for nonblocking read my %children; $SIG{CHLD} = sub { # don't change $! and $? outside handler local ($!, $?); my $pid = waitpid(-1, WNOHANG); return if $pid == -1; return unless defined $children{$pid}; delete $children{$pid}; cleanup_child($pid, $?); }; while (1) { my $pid = fork(); die "cannot fork" unless defined $pid; if ($pid == 0) { # ... exit 0; } else { $children{$pid}=1; # ... system($command); # ... } }

UPDATE: In my opinion it's essential to understand that fork does a 1-to-1-process copy. After that fork you have two processes with the same "Perl source code", just continuing to run at different positions in the code. (The if ($pid == 0) {).

That does also mean that there is a %children hash in the child process even when only meaningfully used by the parent for child bookkeeping. But, e.g. in the currently spawned child you could ask the child's copy of %children which other child processes were spawned and not reaped just until its own birth. A kind of "I do have the following older siblings".

Regards
McA


Comment on Re: Fork() Function
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2014-08-28 04:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (256 votes), past polls