Perl 系统子程序和INT信号的问题

Perl 系统子程序和INT信号的问题,perl,Perl,我的Perl脚本中有一个INT信号处理程序。当Perl脚本位于系统调用的中间时,将不执行INT。为什么? 考虑: $ perl5.12/bin/perl -E "$(cat <<EOF \$SIG{INT} = sub {say q(trapped INT); exit}; say q(sleeping ...); system q(sleep 10000); # INT at this point is not caught by Perl. EOF)"

我的Perl脚本中有一个INT信号处理程序。当Perl脚本位于系统调用的中间时,将不执行INT。为什么?

考虑:

$ perl5.12/bin/perl -E "$(cat <<EOF

    \$SIG{INT} = sub {say q(trapped INT); exit};
    say q(sleeping ...);
    system q(sleep 10000); # INT at this point is not caught by Perl.

EOF)"
sleeping ...

您可以通过检查来检测
system()
子进程是否被
SIGINT
终止,如下所示:

use POSIX qw(SIGINT);

sub interrupt {
    say "trapped INT";
    exit;
}

$SIG{INT} = \&interrupt;

say "sleeping";
system ("sleep 100");

if (($? & 127) == SIGINT) {
        interrupt();
} elsif ($?) {
        say "subprocess failed, status $?";
}
当外部命令运行时,perl会忽略
INT
QUIT
信号,请参阅。

调用system()时,正在执行的任何操作都可以控制终端。通过键盘控件向其发送任何信号都将发送到正在执行的进程(在本例中为系统的sleep命令)

在Perl脚本中捕获信号并对其进行处理只能在该脚本运行时起作用。要在Bash中设置陷阱,可以使用
trap“command”信号

$ perl -e'system("trap \"echo Trapped\" SIGINT; sleep 10");'
^CTrapped

如果这是真的,那么下面的代码不会对^C发出警告:
使用IPC::Open3$SIG{INT}=sub{warn(“INT”)};open3('&STDOUT','>&STDERR',q{perl-e'$SIG{INT}=“IGNORE”;sleep5'});一段时间!waitpid(-1,0)和&$!{EINTR}
如Andy所述,未调用处理程序的原因是
system
在运行时将
SIGINT
SIGQUIT
设置为
IGNORE
use POSIX qw(SIGINT);

sub interrupt {
    say "trapped INT";
    exit;
}

$SIG{INT} = \&interrupt;

say "sleeping";
system ("sleep 100");

if (($? & 127) == SIGINT) {
        interrupt();
} elsif ($?) {
        say "subprocess failed, status $?";
}
$ perl -e'system("trap \"echo Trapped\" SIGINT; sleep 10");'
^CTrapped