fork

fork
This function creates two processes out of one by invoking the
fork(2) syscall. If it succeeds, the function
returns the new child process’s ID to the parent process and 0 to the
child process. If the system doesn’t have sufficient resources to
allocate a new process, the call fails and returns undef. File descriptors (and sometimes locks
on those descriptors) are shared, while everything else is copied—or at
least made to look that way.
In ancient versions, unflushed buffers remain unflushed in both
processes, which means you might need to set $| on one or more filehandles earlier in the
program to avoid duplicate output.
A nearly bulletproof way to launch a child process while checking for “cannot fork” errors would be:
use Errno qw(EAGAIN);
FORK: {
if ($pid = fork) {
# parent here
# child process pid is available in $pid
}
elsif (defined $pid) { # $pid is zero here if defined
# child here
# parent process pid is available with getppid
}
elsif ($! == EAGAIN) {
# EAGAIN is the supposedly recoverable fork error
sleep 5;
redo FORK;
}
else {
# weird fork error
die "Can't fork: $!";
}
}These precautions are not necessary on operations that do an
implicit fork(2)—such as system, backticks, or opening a process as a filehandle—because Perl automatically retries a fork on a temporary ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access