本文介绍了如何为 Perl 系统调用指定超时限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我的系统调用会进入永无止境的状态.为了避免我希望能够在指定的时间后中断通话.

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.

有没有办法指定system?

Is there a way to specify a timeout limit to system?

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

为了可移植性,我希望从 Perl 代码中实现超时,而不是使用某些特定于操作系统的函数,例如 ulimit.

I want the timeout to be implemented from within Perl code for portability, and not using some OS specific functions like ulimit.

推荐答案

参见 报警功能.来自 pod 的示例:

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
}

CPAN 上有一些模块可以更好地包装这些模块,例如:Time::Out

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
}

这篇关于如何为 Perl 系统调用指定超时限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 12:07
查看更多