I frequently use the following pattern to set an upper bound to the running time of a particular code fragment in Perl:
my $TIMEOUT_IN_SECONDS = 5;
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm($TIMEOUT_IN_SECONDS);
# do stuff that might timeout.
alarm(0);
};
if ($@) {
# handle timeout condition.
}
My questions:
- Is this the right way to do it?
- Are there any circumstances under which the running time can exceed $TIMEOUT_IN_SECONDS, or is the above method bullet-proof?
You probably want to look at Sys::SigAction. I haven’t used it myself, but it has some glowing reviews.
One thing to watch out for is if “stuff that might timeout” uses
sleeporalarmitself. Also, in the error handling code, I assume you’re prepared for errors other than a timeout.