14.4 Using fork
Still another way of creating an additional process is to clone the current Perl process using a UNIX primitive called
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
The simplest of these is the
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 to do because the Perl program is long gone.
Another way of looking at this is that the
# METHOD 1... using system:
system("date");
# METHOD 2... using fork/exec:
unless (fork) {
# fork returned zero, so I'm the child, and I exec:
exec("date"); # child process becomes the date command
}
Using
if (!defined($kidpid = fork())) {
# fork returned undef, so failed
die "cannot fork: $!";
} elsif ($kidpid == 0) {
# fork returned 0, so this branch is the child
exec("date");
# if the exec fails, fall through to the next statement
die "can't exec date: $!";
} else {
# fork returned neither 0 nor undef,
# so this branch is the parent
waitpid($kidpid, 0);
}
If this all seems rather fuzzy to you, you should probably study up on the fork (2) and exec (2) system calls in a traditional UNIX text, because Perl is pretty much just passing the function calls right down to the UNIX system calls.
The
unless (defined ($pid = fork)) {
die "cannot fork: $!";
}
unless ($pid) {
unlink </tmp/badrock.*>; # blast those files
exit; # the child stops here
}
# Parent continues here
waitpid($pid, 0); # must clean up after dead kid
Without the
The |
|