14.4. Using fork

Still another way of creating an additional process is to clone the current Perl process using a UNIX primitive called fork. The fork function simply does what the fork (2) system call does: it creates a clone of the current process. This clone (called the child, with the original called the parent) shares the same executable code, variables, and even open files. To distinguish the two processes, the return value from fork is zero for the child, and nonzero for the parent (or undef if the system call fails). The nonzero value received by the parent happens to be the child's process ID. You can check for the return value and act accordingly:

if (!defined($child_pid = fork())) {
    die "cannot fork: $!";
} elsif ($child_pid) {
    # I'm the parent
} else {
    # I'm the child
}

To best use this clone, we need to learn about a few more things that parallel their UNIX namesakes closely: the wait, exit, and exec functions.

The simplest of these is the exec function. It's just like the system function, except that instead of firing off a new process to execute the shell command, Perl replaces the current process with the shell. (In UNIX parlance, Perl exec's the shell.) After a successful exec, the Perl program is gone, having been replaced by the requested program. For example,

exec "date";

replaces the current Perl program with the date command, causing the output of the date to go to the standard output of the Perl program. When the date command finishes, there's nothing more ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.