CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Timeout - local $SIG{ALRM}: Edit Log



ogit
Novice

Feb 15, 2017, 9:52 AM


Views: 2145
Timeout - local $SIG{ALRM}

Hi

I have two pieces of code below. The first alarm works perfectly using sleep. However the second alarm does not trigger. Any idea's how to resolve the second piece of code where the gethostbyaddr won't trigger the alarm?

Code
use strict; 
use warnings;
use Net::IP;
use Net::DNS;
use Socket qw( AF_INET inet_aton );

#FIRST PIECE OF CODE - WORKS PERFECTLY WITH sleep

print "Test 1 - alarm with sleep - works ok\n";
my @time=(3,5,8,2);
LABELME: foreach my $t (@time)
{
eval {
local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
print "Start $t\n";
alarm(4);
sleep $t;
alarm(0);
print "done with $t\n";
};

if ($@) {
die unless $@ eq "alarm\n"; # propagate unexpected errors
print "timeout\n";
next LABELME;
}
else {
# didn't
}
}
print "All Done Test 1!\n";

#SECOND PIECE OF CODE - DOES NOT WORK WITH alarm
print "\n\nTest 2 - alarm with gethostbyaddr - does not work ok\n";
my @time2=("192.168.100.34","192.168.42.14","192.168.100.4","192.168.100.31");
LABELME: foreach my $t (@time2)
{
eval {
local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
print "Start $t\n";
alarm(2);
my $name = gethostbyaddr(inet_aton($t), AF_INET);
alarm(0);
print "done with $t\n";
};

if ($@) {
die unless $@ eq "alarm\n"; # propagate unexpected errors
print "timeout\n";
next LABELME;
}
else {
# didn't
}
}
print "All Done Test 2!\n";

#THIRD PIECE OF CODE - WORKAROUND
print "\n\nTest 3 - gethostbyaddr workaround on Windows - A Lot Faster. alarm not used \n";
my $c10 = chr(10);
my $name = "";
my @time3=("192.168.100.34","192.168.42.14","192.168.100.4","192.168.100.31");
LABELME: foreach my $t (@time3)
{
print "Start $t\n";
my $data =`nslookup $t 2> nul`;
$data=~ s/$c10/\~/g; #get rid of trailing newlines
$data=~ s/.*Name:[ ]*//;
$data=~ s/~.*//;
$data=~ s/Server: .*//;
$name = $data;
if ($name eq "")
{
$name = $t;
}
print "done with $t\n";
}
print "All Done Test 3!\n";



(This post was edited by ogit on Feb 16, 2017, 2:52 AM)


Edit Log:
Post edited by FishMonger (Veteran) on Feb 15, 2017, 11:13 AM
Post edited by FishMonger (Veteran) on Feb 15, 2017, 11:14 AM
Post edited by ogit (Novice) on Feb 16, 2017, 2:52 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives