gpt4 book ai didi

perl - ForkManager SIGINT 只杀死 fork 中的当前进程

转载 作者:行者123 更新时间:2023-12-01 23:10:03 26 4
gpt4 key购买 nike

当我杀死一个使用 ForkManager 的 perl 进程时,我希望所有子进程都死掉。在下面的代码中,如果我运行它并在 sleep 行运行时按 ctrl+c ,则 sleep 进程被终止,但 print 然后在脚本结束之前同时执行所有行。理想情况下,我希望中断立即停止所有执行。我能做什么?

#!/usr/bin/perl -w
use Parallel::ForkManager;

main {
my $fork1 = new Parallel::ForkManager(8);
while (1) {
$fork1->start and next;
system("sleep 15s");
print "Still going!"
$fork1->finish;
}
fork1->wait_all_children;
}

最佳答案

根据perldoc system , system 实际上忽略了 SIGINT 和 SIGQUIT:

Since SIGINT and SIGQUIT are ignored during the execution of system, if you expect your program to terminate on receipt of these signals you will need to arrange to do so yourself based on the return value.

因此,如果您希望您的进程在 system 调用期间 SIGINT 停止执行,您需要自己实现该逻辑:

#!/usr/bin/perl -w
use Parallel::ForkManager;

main {
my $fork1 = new Parallel::ForkManager(8);
while (1) {
$fork1->start and next;
print "Sleeping...";
system("sleep 15s") == 0 or exit($?);
print "Still going!";
$fork1->finish;
}
fork1->wait_all_children;
}

或者更合理的方法是使用 Perl 内置的 sleep :

#!/usr/bin/perl -w
use Parallel::ForkManager;

main {
my $fork1 = new Parallel::ForkManager(8);
while (1) {
$fork1->start and next;
print "Sleeping...";
sleep 15;
print "Still going!";
$fork1->finish;
}
fork1->wait_all_children;
}

关于perl - ForkManager SIGINT 只杀死 fork 中的当前进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31278202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com