On Mon, Jul 13, 2009 at 22:57, Jenn G.<practicalp...@gmail.com> wrote:
> Hello,
>
> From the code below:
>
>  eval {
>    local $SIG{ALRM} = sub { die "TIMEOUT\n" };
>    alarm($seconds);
>    ... code to execute with timeout here ...
>    alarm(0);  # cancel alarm (if code ran fast)
>  };
>  alarm(0);    # cancel alarm (if eval failed)
>
>
> Is the second alarm(0) needed or not?
> In my before experience, I used only one alarm(0) in eval {  }.
snip

Then you have opened yourself up to problems:

#!/usr/bin/perl

use strict;
use warnings;

eval {
        local $SIG{ALRM} = sub { die "timeout\n" };
        alarm 1;
        die "oops";
        alarm 0;
};
select undef, undef, undef, 2;
print "no problem\n";

I typically write it like this:

#!/usr/bin/perl

use strict;
use warnings;

sub timeout {
        my ($wait, $code, $timedout, $error) = (@_,
                sub { warn $@ }, sub { die $@ });

        eval {
                local $SIG{ALRM} = sub { die "timeout\n" };
                alarm $wait;
                $code->();
                alarm 0;
                1;
        } or do {
                alarm 0; #ensure that alarm is not still set
                #raise error if it isn't a timeout
                if ($@ eq "timeout\n") {
                        $timedout->();
                } else {
                        $error->();
                }
        };
}

timeout 1,
        sub { die "oops\n"         },
        sub { warn "timeout out\n" },
        sub { warn "died with $@"  };

timeout 1,
        sub { select undef, undef, undef, 2 },
        sub { warn "timeout out\n"          },
        sub { warn "died with $@"           };

timeout 1,
        sub { print "normal execution\n" },
        sub { warn "timeout out\n"       },
        sub { warn "died with $@"        };

timeout 1, sub { select undef, undef, undef, 2 };
timeout 1, sub { die "and here it ends" };

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to