Perl fork()
Forking in perl is a nice thing to do, and for some it’s a hard thing to understand. It can be pretty easy to get lost especially since there are 100 ways to the same thing. I’m going to attempt to explain a little bit of the inner workings of fork() in Perl.
First you have to understand what fork() returns. When you do:
my $pid = fork();
If it is the parent, $pid will be assigned the PID of the child.
If it is the child, $pid will be assigned 0.
If it cannot fork anymore because of no resources, $pid will be undefined.
To help show how a fork() program works, I’m going to use this sample script:
#!/usr/bin/perl
my $pid = fork();
if (not defined $pid) {
print “resources not avilable.\n”;
} elsif ($pid == 0) {
print “IM THE CHILD\n”;
sleep 5;
print “IM THE CHILD2\n”;
exit(0);
} else {
print “IM THE PARENT\n”;
waitpid($pid,0);
}
print “HIYA\n”;
If run, you will see this:
$ ./f.pl
IM THE CHILD
IM THE PARENT
- sleep for 5 seconds -
IM THE CHILD2
HIYA
This is a pretty simple script and self explanatory. It starts out with the fork and then checks the value of $pid through the if statements and executes the block of code accordingly. What you really have to understand is that when fork() is called, you now have 2 programs that are the same. So in this example, when we do my $pid = fork(); you now have 2 processes running. Each process will run the code. It looks like $pid is only being assigned one value here but it is actually being assigned two or even three values (undefined if necessary). When the parent runs checking through the if statements, it will catch on the last else statement here because $pid is assigned PID of the child. When the child runs through this block of code, it will catch on the if ($pid == 0) because the $pid is assigned 0 for a child. The waitpid() call just waits for the child to exit. If you do not do this it will become a zombie (defunct) process, which means it has become detached from it’s parent.
So here is exactly what happens when you run this:
- The program forks, you now have 2 processes, one is the child, one is the parent.
- if (not defined $pid) gets run on both processes, and die’s if resources aren’t available.
- elsif ($pid == 0) gets run on both processes, if its the child, print “IM THE CHILD”, sleep for 5 seconds and then print “IM THE CHILD 2″ and exit(0);
- While the above statement is running on the child, the parent is going along with the else {} block of code and prints “IM THE PARENT” and then waits for the child to exit.
NOTE: The exit(0) in the child block is very important.. you need the child to exit its process when it is done, so it will no longer exist.
fork
首先说说 fork 函数。这个函数用来创建一个进程,不过创建方法有些不太好理解。 先看下面的程序 fork-test.pl。我是用perl写的,不过相同的功能也可以用 C 来完成。