perl 调用 shell——中断 ^C 停止 shell,而不是 perl

发布于 2024-10-21 18:23:00 字数 137 浏览 6 评论 0原文

我想使用 Perl 脚本来批处理由 system() 调用的重复操作。当出现问题并且我想中断此脚本时,^C 会被 shell 捕获,停止任何作业,而 Perl 脚本会愉快地进行下一个作业。

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

I want to use a Perl script to batch a repetitive operation which is invoked with system(). When something goes wrong and I want to interrupt this script, the ^C is captured by the shell, stopping whatever job, and the Perl script goes merrily along to the next one.

Is there a way I can invoke the job so that an interrupt will stop the Perl script?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤寂小茶 2024-10-28 18:23:01

您可以检查$?来查看系统执行的命令是否因信号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

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

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";
}

参考文献:perldoc system for $? 处理和 system() 调用; perldoc perlvar 了解有关 $? 的更多详细信息

You can check $? to see whether the command executed by system died from signal 2 (INT):

Here's a full example of parsing $?:

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

Therefore the exact check you want is:

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";
}

References: perldoc system for $? handling and system() call; perldoc perlvar for more details on $?

方圜几里 2024-10-28 18:23:01

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

use autodie qw(:all);

它的程序将按预期中止:

"…" died to signal "INT" (2) at … line …

您可以使用 Try::Tiny 以便自行清理或使用不同的消息。

You are not checking the return value of system. Add to your parent program:

use autodie qw(:all);

and it program will abort as expected:

"…" died to signal "INT" (2) at … line …

You may catch this exception with Try::Tiny in order to clean-up on your own or use a different message.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文