2013-11-28 13 views
0

现在我正在为我的传感器网络使用Perl-TK设计一个GUI。 主要问题是,有时我的低功耗有损网络遭受数据包丢失。在这种情况下,我的perl程序在握手时就会出现问题。握手在不同的过程中运行。我想在没有收到数据包时关闭用户并关闭线程Perl:UDP数据包接收超时处理与进程

是否有解决方案来实现kill进程的任何超时?

编辑: 它与主循环一起工作。但是在一个特定的过程中它不起作用,程序停止运行并且终端丢弃“闹钟”。 半结果是:

#!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: - [email protected]"; 
     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; 
} 

编辑2: Can not use alarm in threads...所以我要测量的连接超时。

回答

0

您可以使用alarm和信号捕获发生的异常。 alarm原意是套接字连接,但它可以用于任何需要一段时间来运行:

eval { 
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required 
    alarm $timeout; 
    $nread = sysread SOCKET, $buffer, $size; 
    alarm 0; 
}; 
if ([email protected]) { 
    print ("Timeout occurred") unless [email protected] eq "alarm\n"; # propagate unexpected errors 
    # timed out 
} 
else { 
    # didn't 
} 
+0

我插入这一点,它不会破口大骂:'code' $ tempsock - >发送(“asdasd” ); local $ SIG {ALRM} = sub {die“alarm \ n”}; #NB:\ n required \t \t \t \t \t \t alarm $ conn_timeout; \t \t \t \t \t \t $ tempsock-> recv($ tempdata,16); ($ @){ print(“超时发生”),除非$ @ eq“alarm \ n”;如果($ @){ print #传播意外错误 #超时 } – Nolex

+0

什么?我不明白,重述一下 – nrathaus

+0

对不起,我是初学者,我想在这里写下我的代码,我该如何插入格式化的源代码? :)正如你在上面看到的那样...... – Nolex