in reply to Forks/Threads

fork

Basically, you call it once, it returns twice. If it's the child, it returns 0. If the parent, returns the child's PID. So, from Camel:

if ($pid = fork) { # parent here. } elsif (defined $pid) { #child here. }
Left out some error checking stuff. make sure you wait for your child processes, or your parent will terminate and leave the kids hangin. Read up on fork, wait, and check out $SIG{CHLD} for handling forks. It's a confusing subject at first, but you'll soon pick it up.

Enjoy!

Trinary

Replies are listed 'Best First'.
Re: Re: Forks/Threads
by Anonymous Monk on Feb 05, 2001 at 08:51 UTC
    Thanks for the pointers! They helped a lot. So I've written a little test program to play with the forks and have included it below. Is there any problem with the way I'm keeping track of the max amount of forks to run at a given time? It seems to work fine but was wondering if there's something I'm not aware of or perhaps a better way.

    my $max_children = 10; # max number of children my $num_children = 0; # number we have now foreach $item (@items) { if( my $p = fork() ) { if ($num_children >= $max_children) { $dead_child = wait; $num_children--; } $num_children++; # child count } else { #do some sort of child processing last; # We want out of the loop } }

    Edit: 2001-03-03 by neshura