有时我的系统调用会进入一个永久的状态。为了避免这种情况,我希望能够在指定的时间后退出调用。
是否有一种方法可以为 system
指定超时限制?
system("command", "arg1", "arg2", "arg3");
我希望从Perl代码中实现超时,以便提高可移植性,而不是使用一些特定于操作系统的函数,比如ulimit。
有时我的系统调用会进入一个永久的状态。为了避免这种情况,我希望能够在指定的时间后退出调用。
是否有一种方法可以为 system
指定超时限制?
system("command", "arg1", "arg2", "arg3");
我希望从Perl代码中实现超时,以便提高可移植性,而不是使用一些特定于操作系统的函数,比如ulimit。
alarm
函数。下面是来自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
}
CPAN上有一些模块可以更好地包装它们,例如: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
}
那么 System::Timeout 呢?
这个模块扩展了
system
,允许在指定秒数后超时。
timeout("3", "sleep 9"); # timeout exit after 3 seconds
我之前在Perl + Linux中使用了timeout
命令,你可以像这样测试一下:
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";
}
4.317秒后的输出结果:
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
timeout
命令是所有主要的“普通”Linux发行版(据我所知)的一部分,也是coreutils的一部分。