Use eval To Timeout a Section Of Code
Date : April 16, 2003
eval { local $SIG{__DIE__} = "DEFAULT"; local $SIG{ALRM} = sub { die "timeout" }; # Tells OS to send alarm signal after 10 secs alarm(10); # your chunk of code that could time out while(1) { # do something } }; alarm(0); if ($@ =~ /timeout/) { print "Timed out"; } elsif ($@) { # some other error caught } # the rest of your code here
Note:
- Set the alarm inside the eval.
- Can’t use eq on $@ since it will contain something like “timeout at foo.pl line 10”. Have to use pattern.
Tags:
Perl