perl调用shell-- interrupt ^ C停止shell,而不是perl

Ed *_*yer 2 shell perl interrupt-handling

我想使用Perl脚本批处理用system()调用的重复操作.当出现问题并且我想要中断这个脚本时,shell会捕获^ C,停止任何工作,并且Perl脚本会快速地转到下一个脚本.

有没有办法可以调用作业,以便中断将停止Perl脚本?

DVK*_*DVK 9

您可以检查$?系统执行的命令是否死于信号2(INT):

这是解析的完整示例$?:

my $rc=system("sleep 20"); 
my $q=$?; 
if ($q == -1) { 
    print "failed to execute: $!\n"
} elsif ($? & 127) { 
    printf "child died with signal %d, %s coredump\n",  
           ($q & 127), ($q & 128) ? 'with' : 'without';
} else { 
    printf "child exited with value %d\n", $q >> 8;
}
# Output when Ctrl-C is hit: 
# child died with signal 2, without coredump
Run Code Online (Sandbox Code Playgroud)

因此,您想要的确切检查是:

my $rc=system("sleep 20"); 
my $q=$?; 
if ($q != -1 &&  (($q & 127) == 2) && (!($? & 128))) { 
        # Drop the "$? & 128" if you want to include failures that generated coredump
    print "Child process was interrupted by Ctrl-C\n";
}
Run Code Online (Sandbox Code Playgroud)

参考文献:用于处理和呼叫的perldoc系统 ; perldoc perlvar了解更多详情$?system()$?


dax*_*xim 5

你没有检查的返回值system.添加到您的父程序:

use autodie qw(:all);
Run Code Online (Sandbox Code Playgroud)

它的程序将按预期中止:

"…" died to signal "INT" (2) at … line …
Run Code Online (Sandbox Code Playgroud)

您可以使用Try :: Tiny捕获此异常,以便自行清理或使用其他消息.