方便理解,Perl的fork函数派生子进程的过程:
- #!/usr/bin/perl -w
- # wangxiaoyu#live.com
- use strict;
- defined(my $pid=fork()) or die "Fork process failured:$!\n";
- unless($pid)
- {
- # This is the child process.
- system "date";
- sleep(3);
- print ("Exit child after 3 seconds wait!\n");
- exit();
- }
- # This is the parent process.
- waitpid($pid,0);
- system "date";
- print ("exit parent!\n");
程序执行结果如下:
# perl perl-fork02.pl
Wed Aug 4 22:51:38 HKT 2010
Exit child after 3 seconds wait!
Wed Aug 4 22:51:41 HKT 2010
exit parent!
#
如果不在父进程中提供waitpid函数的话,父进程会在成功创建子进程后不等待子进程执行完毕,立即执行其余的代码,这样的话执行的结果如下:
# perl perl-fork02.pl
Wed Aug 4 22:50:25 HKT 2010
Wed Aug 4 22:50:25 HKT 2010
exit parent!
# Exit child after 3 seconds wait!
本文转自xiaoyuwang 51CTO博客,原文链接:http://blog.51cto.com/wangxiaoyu/367589,如需转载请自行联系原作者