문제

I try to achieve a timer with several loops as below

while ( $try < 3) {
    eval {
        local $SIG{ALRM} = {};
        alarm 3;
        $ret = # sending request and wait for response
        alarm 0;
    }
    last if defined($ret);
    $try++;
}

But actually, when the alarm expired, the whole 'while' loop got interrupted, and the loop didn't happen at all.

Where I got the thing wrong?

도움이 되었습니까?

해결책

You need to set an ALRM Handler, just like the alarm docs demonstrate:

for (1..3) {    
    print "Loop $_\n";

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

        my $count = int rand 10;
        print "Is $count < 5?\n"; 
        sleep $count;

        alarm 0; #cancel the alarm if does not hang
    };

    if ($@) {
        die unless $@ eq "alarm\n";   # propagate unexpected errors
    } else {
        print "Our code succeeded\n";
        last;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top