2013-12-17 36 views
0

我正在尋找一種在即時搜索活動日誌的while循環中引入超時的方法。在一個文件句柄while循環中的Perl超時

我擔心這可能是不可能的,因爲我下面的嘗試總是會超時,因爲我正在偏離正在進行的文件句柄日誌搜索,因此未找到或未找到日誌字符串。

有沒有什麼辦法解決這個問題,沒有太多的編輯,我說這是因爲下面的代碼段是爲了在fork分支中運行(因爲我有一個類似的會話同時運行)。

這裏是我可憐的企圖......

my $countD  = 0; 
my $Dtimeout  = 120; 
my $DNOTComplete = 0; 

while (<$log_DUT>) { 
    $fh_DUT->print($_); 
    last if m/standby handle h/; 
    $countD++; 
    sleep(1); 
    if ($countD > $Dtimeout) { 
     $DNOTComplete = 1; 
     last; 
    } 
} 

回答

2

這是你在找什麼?

my $countD = 0; 
my $Dtimeout = 120; 
my $DNOTComplete = 0; 

eval { 
    local $SIG{ALRM} = sub { die "Timeout" }; # alarm handler 
    alarm($Dtimeout); # start alarm 
         # kernel will send us SIGALRM 
         # after $Dtimeout 
    while(<$log_DUT>) { 
     $fh_DUT->print($_); 
     last if m/standby handle h/; 
     $countD++; 
    } 

    alarm(0); # cancel alarm 
}; 
if ([email protected] =~ /^Timeout/) { 
    # it was timeout 
    # handler called 
    # and died inside eval 
    $DNOTComplete = 1; 
} 
+0

非常感謝奧列格·G,這正是我所期待的,它的工作原理一種享受!再次感謝。 – MikG

1

您正在尋找alarm

例:

#!/usr/bin/perl 

use strict; 
use warnings; 

local $SIG{ALRM} = sub { die "alarm!\n" }; 

alarm(5); 

while (1) { 
    print scalar localtime, "\n"; 
    sleep 1; 
} 
alarm(0); 

OUTPUT:

$ perl test.pl 
Tue Dec 17 08:53:57 2013 
Tue Dec 17 08:53:58 2013 
Tue Dec 17 08:53:59 2013 
Tue Dec 17 08:54:00 2013 
Tue Dec 17 08:54:01 2013 
alarm!