- 论坛徽章:
- 0
|
各位好:
我尝试用Parallel::ForkManager去做并发处理,同时ping多个主机,然后将结果记录到变量$global中。
但是执行的结果是,对每台主机的ping操作都完成,但是$global变量一直为空,按照逻辑来说,每次执行ping主机的操作后,都会将结果记录到$global->{$ip}中,所以我的预期是,$global变量一定会有值的。
但是用Parallel::ForkManager之后,$global变量确实没有值,请问一下,是我哪个地方做得有问题?
谢谢!
注:去掉Parallel::ForkManager的几行之后,$global变量就有内容了。
执行结果如下:
[teamsun@dev rcs]$ perl rcs.pl -check -configfile=test
### @lines: [
### '3.3.3.10',
### '3.3.3.11',
### '3.3.3.12'
### ]
2010-06-09 10:46:27 --- wait for child process
2010-06-09 10:46:27 --- ok, ping 3.3.3.12 sucessful
2010-06-09 10:46:27 --- ok, ping 3.3.3.10 sucessful
2010-06-09 10:46:30 --- error, can not ping 3.3.3.11
2010-06-09 10:46:30 --- $global is empty!
源代码如下:
use strict;
use warnings;
use diagnostics;
use Smart::Comments '###';
use Config;
use Net::Ping::External qw(ping);
use File::Spec::Functions;
use Data::Dumper qw(Dumper);
use Parallel::ForkManager;
my $global;
sub start {
my @lines;
......
my $pm = new Parallel::ForkManager(300);
foreach my $ip (@lines) {
#此处用fork,加快执行速度
$pm->start and next;
forkCheck($line);
$pm->finish;
}
notify ( "debug" => "wait for child process");
$pm->wait_all_children;
if (defined $global) {
notify ( "debug" => "write \$global to file");
}
else {
notify ( "error" => "\$global is empty!");
}
}
sub forkCheck {
my ($ip) = @_;
#先PING一下,如果不通,直接跳过
my $alive = ping(host => $ip , timeout => 5);
if ( $alive ) {
notify ( "debug" => "ok, ping $ip sucessful");
my %hash = (
ip => $ip,
);
$global->{ok}->{$ip} = { %hash };
}
else {
#退出,记录错误信息,然后继续下一个
notify ( "debug" => "error, can not ping $ip");
my %hash = (
ip => $ip,
reason => "can not ping $ip",
);
$global->{error}->{$ip} = { %hash };
return;
}
} |
|