in reply to Waiting for Alarm

alarm does wake the program in sleep, at least on my perl, v5.10.0 built for MSWin32-x86-multi-thread.

Here is the code

use strict; sub Call_with_Timeout{ my ($TIMEOUT, $CODEREF) = @_; eval { local $SIG{ALRM} = sub { die "alarm time out" }; alarm $TIMEOUT; $CODEREF->(); # Whatever needs to be done alarm 0; 1; # return value from eval on normalcy } or return -1; # Timeout happened return 1; # OK } my $t=Call_with_Timeout(3, sub{ sleep 3, print "$_.\n" for 1..2}); print "Timed out=$t;\n";
prints
Timed out=-1;
Which means that the alarm woke it up.

     "As you get older three things happen. The first is your memory goes, and I can't remember the other two... " - Sir Norman Wisdom

Replies are listed 'Best First'.
Re^2: Waiting for Alarm
by n8ur (Acolyte) on Feb 16, 2008 at 18:21 UTC
    When I tried using sleep in the loop, it bombed out after the first alarm -- I got one print from the handler, and then the program exited. However, I just tried again with this:

    #!/usr/bin/perl
    
    use Time::HiRes qw ( setitimer ITIMER_REAL time );
    my $count;
    
    $SIG{ALRM} = sub { print time, "\n" };
    setitimer(ITIMER_REAL, 1, 1);
    
    while (1) {
            sleep 1;
            }
    
    

    and it worked fine. If this is reliable, it does the job for me. But I wonder why the first time it only worked for the first iteration...

    Thanks!

      Ignore the "my $count" -- that's left over from an earlier experiment. Apart from the while loop, this is based on an example in the Time::HiRes documentation.