Question

Now I am designing a GUI for my sensor network with Perl-TK. The main problem is that sometimes my low power lossy network suffers from packet loss. In that case my perl program stucks for example in the handshake. The handshakes run in different processes. I would like to yell for the user when the packet don't received and close the thread

Is there any solutions for implement any timeout for kill processes?

edit: It works with the main loop. But In a specific process it doesn't work, the program running stopped and the terminal drops "Alarm clock". The half result is:

#!usr/bin/perl
use Thread;
use IO::Socket::IP;
use Net::IP;
use Time::Out qw(timeout);
use warnings;

$conn_timeout = 2;
$th1=Thread->create(\&thr1);
while(1)
    {
        sleep(2);
        print"main proc\n";
    } 
sub  thr1{
 print "thread started\n";
        $temp = '2001:4428:29a::280:e103:1:57a8';
        $ip=Net::IP::ip_expand_address($temp, 6);
        $tempsock = IO::Socket::IP ->new(
                PeerAddr => $ip,
                PeerPort => '52525',
                Proto    => 'udp',
        ) or die "Cannot construct socket, IP address: $ip - error message: - $@";
        print "Socket opened successfully for $ip on port 52525\n";
        $SIG{ALRM} = sub {print "detaching...\n";thr1->detach(); }; # NB: \n required
        alarm $conn_timeout;
        $tempsock ->send("asdasd");
        $tempsock->recv($tempdata, 16);
        alarm 0;
}

edit 2: Can not use alarm in threads... So I have to measure the timeout in the connection.

Was it helpful?

Solution

You can use alarm and signal capture the exception that occurs from it. alarm original intent was socket connections, but it can be used for anything that takes awhile to run:

eval {
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
    alarm $timeout;
    $nread = sysread SOCKET, $buffer, $size;
    alarm 0;
};
if ($@) {
    print ("Timeout occurred") unless $@ eq "alarm\n";   # propagate unexpected errors
    # timed out
}
else {
    # didn't
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top