perl多进程数量控制-信号或者判断pid是否存在
实例的功能就是多进程ping不同的主机,查看主机是否可连通。。试了一把。1.通过子进程返回的CHLD信号
#!/usr/bin/perl -w
use Net::Ping;
use POSIX;
my @ip;
open IN,'ip.txt' or die'error';
@ip=;
close(IN);
my $total=$#ip+1;
my $num=$total;
my $a=0;
my $bam=0;
$SIG{CHLD}=sub{$a--;$bam++};
my %pid;
while($total)
{
if($anew();
my $de=$num-$total;
$ip[$de]=~s/\n//g;
if($p->ping($ip[$de],5))
{
print "$ip[$de] is reachable\n";
}
else{
print "$ip[$de] is noreach\n";
}
$p->close();
exit 0;
}
$a++;
$total--;
}
while($bam >0)
{
while(my $exit_pid=waitpid(-1,WNOHANG) > 0)
{
$bam--;
if(exists($pid{$exit_pid})){delete $pid{$exit_pid};}
}
}
}
my @left=keys %pid;
if(@left)
{
foreach my $j(@left)
{
waitpid($j,0);
}
}
2. 通过判断子进程的pid是否存在
#!/usr/bin/perl -w
use Net::Ping;
use POSIX;
$SIG{CHLD}='IGNORE';
my @ip;
open IN,'ip.txt' or die'error';
@ip=;
close(IN);
my $total=$#ip+1;
my $i;
my %pid;
for($i=0;$i=4)
{
foreach my $j(@pids)
{
delete $pid{$j} unless(kill 0 =>$j);
}
@pids=keys %pid;
}
my $pid=fork();
if($pid)
{
$pid{$pid}=1;
}
else{
my $p=Net::Ping->new();
$ip[$i]=~s/\n//g;
if($p->ping($ip[$i],5))
{
print "$ip[$i] is reachable\n";
}
else{
print "$ip[$i] is noreach\n";
}
$p->close();
exit 0;
}
}
my @left=keys %pid;
while($#left != -1)
{
foreach my $k(@left)
{
delete $pid{$k} unless(kill 0 =>$k);
}
@left=keys %pid;
}
页:
[1]