- 论坛徽章:
- 0
|
#!/usr/bin/perl
# test_proc_3.pl
# test multi process
# create by lianming: 2009-08-12
use strict;
use warnings;
use POSIX ":sys_wait_h";
## == number of proc ==
my $num_proc = 0;
my @proc;
## == number of collected ==
my $num_collect = 0;
my $collect;
## == get the child signal ==
$SIG{CHLD} = sub { $num_proc-- };
for (my $i = 0; $i < 10; $i ++) {
## == fork a new process ==
my $pid = fork();
if (!defined($pid)) {
print "Error in fork: $!";
exit 1;
}
if ($pid == 0) {
## == child proc ==
print "Child $i : My pid = $$\n";
sleep(5);
print "Child $i : end\n";
exit 0;
} else {
#
# 父进程和子进程是一起生成的
#
push(@proc, $pid);
}
#
# 注释的部分你知道在做什么呢?
#
# $num_proc ++;
# ## == if need to collect zombies ==
# if (($i-$num_proc-$num_collect) > 0) {
# while (($collect = waitpid(-1, WNOHANG)) > 0) {
# $num_collect ++;
# }
# }
# do {
# sleep(1);
# } until ($num_proc < 3);
}
#
# 先fork,让所有的子进程全部启动,然后在等所有的进程全部结束
#
foreach (@proc) {
waitpid($_, 0);
}
exit 0;
------------------------注意看时间---------------------------------------------------------------
time perl test.pl
Child 0 : My pid = 21331
Child 1 : My pid = 21333
Child 2 : My pid = 21334
Child 3 : My pid = 21335
Child 4 : My pid = 21336
Child 5 : My pid = 21337
Child 6 : My pid = 21338
Child 7 : My pid = 21339
Child 8 : My pid = 21340
Child 9 : My pid = 21341
Child 0 : end
Child 1 : end
Child 3 : end
Child 2 : end
Child 4 : end
Child 5 : end
Child 6 : end
Child 7 : end
Child 9 : end
Child 8 : end
real 0m5.027s
user 0m0.015s
sys 0m0.012s
--------------------------------------------------------
--------------------以前的版本没有达到多进程节省时间的效果---------------------------------------
time perl test.pl
Child 0 : My pid = 21411
Child 1 : My pid = 21412
Child 2 : My pid = 21413
Child 0 : end
Child 3 : My pid = 21418
Child 1 : end
Child 4 : My pid = 21419
Child 2 : end
Child 5 : My pid = 21420
Child 3 : end
Child 6 : My pid = 21421
Child 4 : end
Child 7 : My pid = 21422
Child 5 : end
Child 8 : My pid = 21423
Child 6 : end
Child 9 : My pid = 21428
Child 7 : end
Child 8 : end
Child 9 : end
real 0m20.029s
user 0m0.016s
sys 0m0.012s
------------------------------------------------------------------------------ |
|