2010-10-19 29 views
24

有时我的系统调用进入一个永无止境的状态。为了避免我希望能够在指定的时间后突破呼叫。如何为Perl系统调用指定超时限制?

有没有办法指定system的超时限制?

system("command", "arg1", "arg2", "arg3"); 

我想要在Perl代码中实现超时以实现可移植性,而不是使用某些操作系统特定的函数(如ulimit)。

+1

这是一个重复多次比我可以指望:http://stackoverflow.com/questions/2679582/how-can-i-kill-a-perl-system-call-after-a -timeout http://stackoverflow.com/questions/1962985/how-can-i-timeout-a-forked-process-that-might-hang http://stackoverflow.com/questions/2423288/ways-to-do -timeouts-in-perl http://stackoverflow.com/questions/3427401/perl-make-script-timeout-after-x-number-of-seconds http://stackoverflow.com/questions/1165316/how-can -i-limit-the-time-in-a-specific-section-of-perl-script只是其中的一小部分。 – Ether 2010-10-19 16:05:58

回答

27

查看alarm函数。从荚果例如:

eval { 
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required 
    alarm $timeout; 
    $nread = sysread SOCKET, $buffer, $size; 
    alarm 0; 
}; 
if ([email protected]) { 
    die unless [email protected] 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 ([email protected]){ 
    # operation timed-out 
} 
+0

这似乎工作,但问题是通过系统调用执行的命令将继续运行,即使父Perl过程已经死亡。有谁知道如何获得由系统调用运行的进程的进程ID /句柄,以便我们可以在Perl脚本结束之前将其终止? – antred 2017-02-17 10:53:29

+1

@antred - 要获得进程ID,则需要使用['fork'](http://perldoc.perl.org/perlfork.html)而不是['system'](http:// perldoc。 perl.org/functions/system.html)。看一下像IPC :: Cmd&IPC :: Run这样的模块,使其更容易(在这种情况下)。 – draegtun 2017-02-19 13:44:37

13

可以使用IPC::Run的运行方法,而不是系统。并设置超时。

3

System::Timeout怎么样?

该模块扩展system以允许在指定秒数后超时。

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

仅当内容移动或更改时,仅链接答案才有用。在回答中加入链接的相关部分,并根据问题进行量身定制。 – miken32 2017-01-31 20:29:26

+0

一个潜在解决方案的链接总是值得欢迎的,但请[在链接周围添加上下文](http://meta.stackexchange.com/a/8259),以便您的同行用户了解它是什么以及它为什么在那里。如果目标网站无法访问或永久离线,请始终引用重要链接中最相关的部分。考虑到仅仅是一个链接到外部网站是一个可能的原因[为什么和如何删除一些答案?](http://stackoverflow.com/help/deleted-answers)。 – FelixSFD 2017-01-31 20:29:36

+1

@ miken32编辑。 – melpomene 2017-01-31 20:53:51