如何通过Perl中的SIGHUP跳转(1)?

bur*_*rsk 3 perl loops signals

我喜欢跳后while(1).怎么做?检查特殊变量并且last不正常,因为while表达式包含阻塞调用,因此如果检查表达式则为时已晚.

#!/usr/bin/perl
use strict;
use warnings;
use feature qw( say );
use sigtrap 'handler', \&hup_handler, 'HUP';
my $counter = 0;
sub hup_handler { say 'HUP!!!'; $counter = 0; return; }
say 'It starts here';
while ( 1 ) {
    sleep( 1 ); # Blocking call is in reality within while expression.
    say ++$counter;
}
say 'It ends here';
Run Code Online (Sandbox Code Playgroud)

pma*_*olm 6

这应该可以通过在信号处理程序中抛出异常,也就是die()来实现.

所以尝试做这样的事情:

say 'It starts here';
eval {
    local $SIG{HUP} = sub { say 'HUP!!!'; $counter = 0; die "*bang*"; }

    while ( 1 ) {
        sleep( 1 ); # Blocking call is in reality within while expression.
        say ++$counter;
    }
}
say 'It ends here';
Run Code Online (Sandbox Code Playgroud)

当然,任何提供更正常的try/catch语法的模块都可以工作.

  • 您可以在我将代码更改为的时候在循环内移动信号处理程序.我从来没有使用过sragtrap pragma,所以我不确定它是否在词法上正常工作.相反,我直接使用%SIG. (2认同)