http://www.perlmonks.org?node_id=981435


in reply to Re: alarm not working
in thread alarm not working

Blocking does not resolve the problem. Here is the code, I am still facing the issue the program is not killed after alarm but sits back waiting and waiting.
my $socket_resp = IO::Socket::INET->new(LocalPort => $response_por +t, Proto => 'udp', Blocking => 1, Timeout => undef); print "FW Machine: Waiting for Command Response On Port $response_ +port\n"; eval { local $SIG{ALRM} = sub { die "Timed Out"; }; alarm 10; while (1) { my $recieved_data; $socket_resp->recv($recieved_data, 1024); alarm 10; my $peer_address = $socket_resp->peerhost(); my $peer_port = $socket_resp->peerport(); if ($peer_address eq $send_ip_address) { my $desti = GetIP(); chomp($recieved_data); print "$peer_address:$peer_port > $desti:$response_por +t => $recieved_data\n"; if ($recieved_data =~ m/^done/i) { last; } } } alarm 0; }; alarm 0; if ($@ =~ /Timed Out/i) { print "Timed-Out waiting for infinite loop to finish\n"; } $socket_resp->close();

Replies are listed 'Best First'.
Re^3: alarm not working
by aitap (Curate) on Jul 13, 2012 at 17:17 UTC

    alarm() on Windows cannot interrupt system calls, so there should be another answer.(see Alphabetical Listing of Perl Functions)

    Can you try the third method from Re: what does timeout mean in IO::Socket::INET ?? It seems to be the right thing.

    Also, I may have misunderstood somethng, but Blocking is set to 1 in your code. If all else fails, the following (ugly) kludge can help:

    my $socket_resp = IO::Socket::INET->new(LocalPort => $response_port, P +roto => 'udp', Blocking => 0, Timeout => undef); ... $received_data=&timeout_recv($socket,1024,10); ... sub timeout_recv { my $return; my $buf; my $cnt=0; for (1..$_[2]) { # $_[2] is timeout $_[0]->recv($buf,$_[1]-$cnt) // 0; # $_[1] is count of bytes to rece +ive $cnt += length $buf; $return .= $buf; return $return if $cnt == $_[1]; sleep 1; # the ugliest line } die "Timed Out"; }

    Sorry if my advice was wrong.