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.
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 }
You can use IPC::Run's run method instead of system. and set a timeout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With