Apr
16

Use eval To Timeout a Section Of Code

By celso

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
};
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.
Categories : Perl

Leave a Comment

You must be logged in to post a comment.