1 #!/bin/perl
2 $return=fork;
3 if ($return == 0){
4 print "this is the child process;return value is $return.\n";
5 exec "/bin/date"or die"exec failed:$!\n";
6 print "this line will never be outputted!\n";
7 }
8 elsif (defined $return){
9 $waitting=wait;
10 print "parent process:return pid is $return.\n";
11 $waitting=wait;
12 print "back in parent process.\n";
13 print "the dead child's pid is $return.\n";
14 }
15 else {
16 die "fork error:$!\n";
17 }
18 print "hello only once.\n";
脚本执行结果:
[root@stationx perl]# perl fork.pl
this is the child process;return value is 0.
Fri May 4 00:21:13 CST 2012
parent process:return pid is 4560.
back in parent process.
the dead child's pid is 4560.
hello only once.
在fork出的子程序中执行了一个exec(利用新代码替换当前进行的代码进行执行操作,执行完后退出,并不返回到该程序中)操作,由于exec执行完之后并不会在回到fork出的那个子程序中去,此时fork出的子程序退出,程序会返回到perl脚本(fork的父进程)中来,当然,fork子程序的pid也返回到了父进程中,然后在进行if、elsif、else结构的判断。
fork函数之所以能区别父进程和子进程,是因为它对不同的进程返回不同的值,对于子进程返回0,对于父进程返回子进程的pid,但是调用fork函数之后不能保证首先执行哪一个进程。脚本中的第九行的作用是:(虚伪的模拟下,先让fork子进程执行完,然后在去执行父进程,但是问题又来了,如果走到elsif的话,说明父进程已经开始工作了,然后exec的执行结果却出现在了父进程执行的时候,让人大费不解!!!难道是因为exec不清楚缓冲区的缘故???这个地方实在不懂。请高人读了该文章后能够指点迷津,小弟不胜感激!)。