利用perl研究fork函数和exec函数
1#!/bin/perl2$return=fork;
3if ($return == 0){
4print "this is the child process;return value is $return.\n";
5exec "/bin/date"or die"exec failed:$!\n";
6print "this line will never be outputted!\n";
7}
8elsif (defined $return){
9$waitting=wait;
10print "parent process:return pid is $return.\n";
11$waitting=wait;
12print "back in parent process.\n";
13print "the dead child's pid is $return.\n";
14}
15else {
16die "fork error:$!\n";
17}
18print "hello only once.\n";
脚本执行结果:
# perl fork.pl
this is the child process;return value is 0.
Fri May4 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不清楚缓冲区的缘故???这个地方实在不懂。请高人读了该文章后能够指点迷津,小弟不胜感激!)。
页:
[1]