#!/usr/bin/perl -w
use POSIX ":sys_wait_h";
our $num = 3000;
our $fnum = 0;
our @childs;
$SIG{CHLD} = \&REAPER;
#if parent get CHLD exit signal, we do $fnum--,
#so while loop will fork another child
sub REAPER {
$fnum--;
#$fnum = 0;
print "fnum--\n";
my $pid; while (($pid = waitpid(-1, WNOHANG)) > 0) {
print "$pid die\n";
}
}
while($num>0){
if($fnum<1000){
my $pid = fork();
if($pid ==0 ){
#child
sleep(int(rand(5)));
#sleep(1);
print "this is a child $num\n";
exit(0);
}
else{
push(@childs,$pid);
print "fnum++\n";
$fnum++;
$num--;
print "fork child $pid\n";
print "fnum is $fnum\n";
}
}
}
foreach(@childs){
waitpid($_,0);
$fnum=0;
}
阅读(788) | 评论(0) | 转发(0) |