Use eval To Timeout a Section Of Code


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:

  1. Set the alarm inside the eval.
  2. Can’t use eq on $@ since it will contain something like “timeout at foo.pl line 10”. Have to use pattern.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.