Getting Down and Dirty with fork
In addition to the high-level interfaces described, Perl provides nearly direct access to the low-level process management system calls of Unix and some other systems so far. If you’ve never done this before,[329] you will probably want to skip this section. While it’s a bit much to cover all this stuff in a chapter like this, let’s at least look at a quick reimplementation of this:
system "date";
Look at how that would be done using the low-level system calls:
defined(my $pid = fork) or die "Cannot fork: $!";
unless ($pid) {
# Child process is here
exec "date";
die "cannot exec date: $!";
}
# Parent process is here
waitpid($pid, 0);Here, we’ve checked the return value from fork, which will be undef if it failed. Usually it will succeed, causing two separate processes to continue to the next line, but only the parent process has a nonzero value in $pid, so only the child process executes the exec function. The parent process skips over that and executes the waitpid function, waiting for that particular child to finish (if others finish in the meantime, they are ignored). If that all sounds like gobbledygook, just remember that you can continue to use the system function without being laughed at by your friends.
When you go to this extra trouble, you will have full control over arbitary pipe creation, rearranging filehandles and noticing your process ID and your parent’s process ID (if knowable). But again, that’s all a bit complicated for this chapter, ...
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