2013-11-28 14 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