How can I specify timeout limit for Perl system call?

Lazer picture Lazer · Oct 19, 2010 · Viewed 14k times · Source

Sometimes my system call goes into a never ending state. To, avoid that I want to be able to break out of the call after a specified amount of time.

Is there a way to specify a timeout limit to system?

system("command", "arg1", "arg2", "arg3");

I want the timeout to be implemented from within Perl code for portability, and not using some OS specific functions like ulimit.

Answer

draegtun picture draegtun · Oct 19, 2010

See the alarm function. Example from pod:

eval {
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
    alarm $timeout;
    $nread = sysread SOCKET, $buffer, $size;
    alarm 0;
};
if ($@) {
    die unless $@ eq "alarm\n";   # propagate unexpected errors
    # timed out
}
else {
    # didn't
}

There are modules on CPAN which wrap these up a bit more nicely, for eg: Time::Out

use Time::Out qw(timeout) ;

timeout $nb_secs => sub {
  # your code goes were and will be interrupted if it runs
  # for more than $nb_secs seconds.
};

if ($@){
  # operation timed-out
}