Question

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?

Was it helpful?

Solution

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;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top