Apr
16
Use eval To Timeout a Section Of Code
Byeval { 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 }; 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.
Leave a Comment
You must be logged in to post a comment.