有时我的系统调用会进入永无止境的状态。为了避免我希望能够在指定的时间后中断通话。
有没有办法将超时限制指定为 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
}
关于perl - 如何为 Perl 系统调用指定超时限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3967470/