Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify timeout limit for Perl system call?

Tags:

perl

system

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.

like image 864
Lazer Avatar asked Oct 19 '10 10:10

Lazer


2 Answers

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 } 
like image 137
draegtun Avatar answered Sep 24 '22 00:09

draegtun


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

like image 40
ysth Avatar answered Sep 22 '22 00:09

ysth