Section 14.6. Getting Down and Dirty with fork

14.6. 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,[*] 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:

[*] Or if you're not running on a system that has support for forking. But the Perl developers are working hard to add forking even on systems whose underlying process model is very different than the one in Unix.

     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, so see the details in the perlipc manpage (and in any good book on application programming on your system) for further information.

Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2003
Pages: 232

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: