如何在Perl中进行超时? [英] Ways to do timeouts in Perl?

查看:84
本文介绍了如何在Perl中进行超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用以下模式来设置Perl中特定代码片段的运行时间上限:

I frequently use the following pattern to set an upper bound to the running time of a particular code fragment in Perl:

my $TIMEOUT_IN_SECONDS = 5;
eval {
    local $SIG{ALRM} = sub { die "alarm\n" };
    alarm($TIMEOUT_IN_SECONDS);
    # do stuff that might timeout.
    alarm(0);
};
if ($@) {
    # handle timeout condition.
}

我的问题:

  • 这是正确的方法吗?
  • 在任何情况下运行时间都可能超过$ TIMEOUT_IN_SECONDS,或者上述方法是否防弹?

推荐答案

您可能想看看 Sys :: SigAction .我本人还没有使用过它,但是它有一些发光的评论.

You probably want to look at Sys::SigAction. I haven't used it myself, but it has some glowing reviews.

要注意的一件事是,可能超时的东西"是使用sleep还是alarm本身.另外,在错误处理代码中,我假设您已经为超时以外的错误做好了准备.

One thing to watch out for is if "stuff that might timeout" uses sleep or alarm itself. Also, in the error handling code, I assume you're prepared for errors other than a timeout.

这篇关于如何在Perl中进行超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆