[Pikes-peak-pm] Firing Off Child Processes

Tim Chambers timc+perl at divide.net
Thu Oct 7 18:07:35 CDT 2004


John Evans wrote:
> ...if fork() is the only option that I have, then I can make it work.

Yes, that's the only option for creating child processes. It's weird, but
not so bad when you get used to it. I've used it a lot. There's plenty of
documentation out there on how to do it. The key to remember is that fork
returns the child pid to the parent and 0 to the child. That's how your
program will know whether it's the parent copy or the child copy. The parent
usually waits for the child to finish. The child does the work, often
exec'ing a program. The parent can fork multiple children. Practice with
smaller examples before tackling bigger, more complex ones to get used to
what's going on. Write debug statements in the examples to convince yourself
you understand the difference between the parent and the child.

Here's a little example I whipped up.

print "simple fork example\n";
our $pid;
unless ($pid = fork) { # this block of code is the child
 print "child: sleeping 3 and printing again...\n";
 sleep 3;
 print "child: now exiting\n";
 exit 0; # always exit at the end of the child code block
}
print "parent: child PID=[$pid]; waiting\n";
our $ret = waitpid $pid, 0;
print "parent: waitpid returned [$ret]\n";

Tom Harrington wrote:

> Then "make -j N" kept multiple copies of the script running in parallel 
> until everything was done.  No sense worrying about fork() ...

Right. TMTOWTDI. Even if you don't have to use Perl to do it. :)

<>< Tim



More information about the Pikes-peak-pm mailing list