Pregunta

I am looking for a way of introducing a timeout within a while loop which is searching an active log on the fly.

I fear this may not be possible as my attempt below will always timeout because I am diverting away from the ongoing file handle log search, and therefore the log string is not found or missed.

Is there any way around this without too much editing, I say this as the piece of code below is meant to function within a fork branch (as I have a similar session running simultaneously).

Here's is my poor attempt...

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;
    }   
}
¿Fue útil?

Solución

Is this what are you looking for?

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 ($@ =~ /^Timeout/) {
    # it was timeout
    # handler called
    # and died inside eval
    $DNOTComplete = 1;
}

Otros consejos

You're looking for alarm

EXAMPLE:

#!/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!
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top