Orzdba's Blog

Think then do it…

【Perl】fork子进程

leave a comment »

Perl中可以通过fork函数来创建一个子进程。如果fork成功的话,这个时候就存在父进程和子进程,接下来2个进程会同时开始执行perl脚本中fork函数后面的代码。例子如下:

#!/usr/local/bin/perl
use Term::ANSIColor;
use strict;
use warnings;
$SIG{CHLD} = ‘IGNORE’; #忽略SIGCHLD信号,回收僵尸子进程
print color(‘green’),”Program started… pid = $$ \n\n”;
print “fork process…\n”;
# 如果fork失败,则返回undefined
defined ( my $child = fork() ) or die “Fork Error : $!\n” ;
# 如果fork成功:
# 如果是父进程,则把生成的子进程PID赋值给$child。
# 如果是子进程,则把0赋值给$child。
if ($child == 0){
print color(‘yellow’),”\n-> child process running …\n”;
print “child process pid : $$ !\n”;
# 退出子进程,如果前面没有对子进程处理的话,那么在父进程还没退出期间,子进程就变成僵尸子进程。
exit 0;
} else {
print color(‘blue’),”\n-> parent process running …\n”;
print “child process pid : $child ; parent process pid : $$ !\n”,color(‘reset’);
}
#sleep(10);
print “\nHello World!\n”;

执行结果如下:

[zhuxu@xentest8-vm1 my_perl_test]$ ./fork.pl

Program started… pid = 30881

fork process…

-> child process running …

child process pid : 30882 !

-> parent process running …

child process pid : 30882 ; parent process pid : 30881 !

Hello World!

[zhuxu@xentest8-vm1 my_perl_test]$

【参考】:Perl fork()

–EOF–

Written by orzdba

四月 8, 2011 at 12:58 pm

Posted in Perl

Tagged with ,

回應文章

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook photo

You are commenting using your Facebook account. Log Out / 變更 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.