Lazer
Lazer

Reputation: 94990

How can I specify timeout limit for Perl system call?

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.

Upvotes: 27

Views: 17107

Answers (4)

Kjetil S.
Kjetil S.

Reputation: 3785

I've just used the timeout command in Perl + Linux before, something you can test like this:

for(0..4){
  my $command="sleep $_";  #your command
  print "$command, ";
  system("timeout 1.1s $command");  # kill after 1.1 seconds
  if   ($? == -1  ){ printf "failed to execute: $!" }
  elsif($?&127    ){ printf "died, signal %d, %scoredump", $?&127, $?&128?'':'no '}
  elsif($?>>8==124){ printf "timed out" }
  else             { printf "child finished, exit value %d", $? >> 8 }
  print "\n";
}

Output after 4.317 seconds:

sleep 0, child finished, exit value 0
sleep 1, child finished, exit value 0
sleep 2, timed out
sleep 3, timed out
sleep 4, timed out

The timeout command is part of all major "normal" Linux distributions a.f.a.i.k, a part of coreutils.

Upvotes: 5

draegtun
draegtun

Reputation: 22570

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
}

Upvotes: 29

John Chain
John Chain

Reputation: 678

How about System::Timeout ?

This module extends system to allow timeout after the specified seconds.

timeout("3", "sleep 9"); # timeout exit after 3 seconds

Upvotes: 4

ysth
ysth

Reputation: 98498

You can use IPC::Run's run method instead of system. and set a timeout.

Upvotes: 15

Related Questions