Subject: | When using multi-threads, it will return with fault. |
Date: | Wed, 19 Dec 2007 19:45:48 +0800 |
To: | bug-Net-Ping [...] rt.cpan.org |
From: | Kinpoo <kinpoo [...] gmail.com> |
When using multi-threads, it will return with fault.
#./ ping.pl 255
...
-- 66.94.234.14 -- -- -- -- -- --
-- ping $host -c 1 -w 2 -- # using system's ping
0 2000 ms
0 2000 ms
0 2000 ms
-- Net::Ping->ping($host) -- # using Net::Ping
1 237.16 ms
1 197.78 ms
1 206.21 ms
-- 66.94.234.5 -- -- -- -- -- --
-- ping $host -c 1 -w 2 --
0 2000 ms
0 2000 ms
0 2000 ms
-- Net::Ping->ping($host) --
0 1259.97 ms
0 190.26 ms
1 775.19 ms
...
#cat ping.pl
#! /usr/bin/perl
use strict;
use warnings;
use threads(stack_size => 17*1024);
use Net::Ping;
use Time::HiRes qw(gettimeofday);
my $end = defined($ARGV[0]) ? $ARGV[0] : 1;
my $t_b = getMilliseconds();
threads->create(\&processPingScan, '66.94.234.' . $_) foreach ((1..$end));
while (threads->list(threads::running)) {
sleep(1); # waiting for threads
}
my $t_e = getMilliseconds();
my $t_u = nearest(0.01, $t_e - $t_b);
print "\nDone!$t_u ms used!\n";
sub processPingScan {
my $host = shift;
my $temp = '';
my $num = 3;
$temp .= "-- ping \$host -c 1 -w 2 --\n";
foreach ((1..$num)) {
my ($ret, $t_u);
if (`ping $host -c 1 -w 2` =~ /time=([\d\.]+)/) {
$ret = 1;
$t_u = $1;
}
else {
$ret = 0;
$t_u = 2000;
}
$temp .= "\t$ret\t$t_u ms\n";
}
$temp .= "\n-- Net::Ping->ping(\$host) --\n";
my $oPing = Net::Ping->new('icmp', 2);
foreach ((1..$num)) {
my $t_b = getMilliseconds();
my $ret = $oPing->ping($host);
my $t_e = getMilliseconds();
my $t_u = nearest(0.01, $t_e - $t_b);
$temp .= "\t$ret\t$t_u ms\n";
}
print "-- $host -- -- -- -- -- --\n$temp\n";
threads->detach();
threads->exit();
}
sub getMilliseconds {
my ($sec, $usec) = gettimeofday();
return $sec*1000 + $usec/1000;
}
sub nearest { # nearest(0.01, 1.123) = 1.12
my ($target, $num) = @_;
my $x;
$target = abs($target);
if ($num >= 0) {
$num = $target * int(($num + 0.5 * $target) / $target);
}
else {
$num = $target * int(($num - 0.5 * $target) / $target);
}
return $num;
}