本文介绍了警报转义Perl'eval'块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Perl脚本,可以自动从各种来源下载内容.它使用alarmeval块中进行下载,因此如果花费的时间太长,尝试将超时:

I have a Perl script that automatically downloads content from various sources. It does the downloading in an eval block with an alarm so that the attempt will time out if it takes too long:

eval {
    alarm(5);
    my $res = $ua->request($req);
    $status = $res->is_success;
    $rawContent = $res->content;
    $httpCode = $res->code;
    alarm(0);
};

这已经工作了多年,但是在进行了一些系统更新后,突然间它停止了工作.相反,它遇到的第一个源超时,我收到以下错误,程序终止:

This has worked for years, but after doing some system updates, all of a sudden it quit working. Instead, the first source it hits that times out, I get the following error and the program terminates:

 Alarm clock

我做错了什么,导致阻止eval突然捕获警报?

What am I doing incorrectly that is preventing eval from catching the alarm all of a sudden?

推荐答案

SIGALRM的默认设置是终止程序,因此您需要对其进行处理.常见的方法是在捕获SIGALRM时发出die并将其转换为eval -ed的异常.

The default for SIGALRM is to terminate the program, so you need to handle it. A common way is to issue a die when SIGALRM is caught, turning it into an exception, which is eval-ed.

eval {
    local $SIG{ALRM} = sub { die "Timed out" };
    alarm(5);
    my $res = $ua->request($req);
    $status = $res->is_success;
    $rawContent = $res->content;
    $httpCode = $res->code;
    alarm(0);
};
if ($@ and $@ !~ /Timed out/) { die }  # re-raise if it is other error

来自 perlipc


关于它的工作方式,我能想到的一件事是,在eval中使用的程序包具有基于alarm的自己的计时器,从而取消了alarm.来自 alarm


As for how it ever worked, the one thing I can think of is that packages used inside eval had their own timers, based on alarm, thus canceling your alarm. From alarm

超时时,它们可能引发了异常,并且您具有预期的行为.此软件包的行为在更新中已更改,现在您的警报可以正常工作并需要处理.当然,这是一个猜测.

They may have thrown exceptions when timing out and you had the expected behavior. This package behavior changed in the update and now your alarm works and needs handling. This is a guess, of course.

这篇关于警报转义Perl'eval'块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:00