perl - 如何在 Perl 中通过 SIGHUP 在 while(1) 之后跳转?

标签 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';

最佳答案

这应该可以通过在您的信号处理程序中抛出一个异常来实现,也就是 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';

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

关于perl - 如何在 Perl 中通过 SIGHUP 在 while(1) 之后跳转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12602252/

相关文章:

linux - 从文本文件中删除包含特定文本的行

perl - Unix 如何读取带有两个连续斜杠的路径名? (例如/home/user//mystuff)

javascript - 使用带数组的循环命名变量

c++ - 将 QAction 连接到插槽

c - 多个线程接收一个信号

php - 网页内目录浏览

perl - 为什么 Perl 以 LIFO 顺序运行 END 和 CHECK block ?

vba - 多个单元格选择,而不是范围

Java - while循环将第一个输出添加到第二个输出

ruby - 在 linux 上的 ruby​​ 中,有没有办法获取捕获信号的 siginfo_t 数据?