Perl从`system`命令转发SIGINT到父进程

Perl从`system`命令转发SIGINT到父进程,第1张

概述如果我有一个长时间运行的系统命令,如apt-cache search< some query>,有没有办法将命令行上通过^ C发送的SIGINT转发到父Perl进程,以便所有子进程都是收获. 此示例没有所需的行为.信号被发送到子进程. #!/usr/bin/env perluse strict;use warnings FATAL => 'all';use autodie;# long 如果我有一个长时间运行的系统命令,如apt-cache search< some query>,有没有办法将命令行上通过^ C发送的SIGINT转发到父Perl进程,以便所有子进程都是收获.

此示例没有所需的行为.信号被发送到子进程.

#!/usr/bin/env perluse strict;use warnings FATAL => 'all';use autodIE;# long running command on ubuntu,produces a ton of output.# replace with your favorite long running commandsystem("apt-cache search hi");print("Perl dID not catch SIGINT even with autodIE\n");

我试图寻找捕获将由系统创建的孩子的pID的方法(“apt-cache search hi&”),但找不到任何东西,所以我尝试分叉并执行该过程并写入信号处理程序.这不起作用,因为apt-cache本身通过克隆系统调用启动了一些进程.手动滚动一些逻辑来遍历流程树的一部分并清理它

#!/usr/bin/env perluse strict;use warnings FATAL => 'all';use autodIE;my $cpID;$SIG{INT} = sub {    kill 'KILL',$cpID;    exit;};# long running command on ubuntu,produces a ton of output.# replace with your favorite long running command$cpID = fork;if ($cpID == 0) {    exec 'apt-cache','search','hi';}print "Perl dID not catch SIGINT even with autodIE\n";

我想基本上我想要的是一种确定系统启动的子进程是否由于SIGINT之类的信号退出的方式,所以我可以让Perl脚本自行清理,或者一种方式来处理子进程并将其收入一种可以干净利落地处理流程管理的奇怪边缘情况的方法.

解决方法 让孩子成为进程组的负责人,然后将信号发送给整个进程组.

#!/usr/bin/perluse strict;use warnings;use autodIE;use POSIX qw( setpgID );my $child_pID;$SIG{INT} = sub {    kill INT => -$child_pID if $child_pID;    exit(0x80 | 2);  # 2 = SIGINT};my $child_pID = fork();if (!$child_pID) {    setpgID($$);    exec 'apt-cache','hi';}WAIT: {   no autodIE;   waitpID($child_pID,0);   redo WAIT if $? == -1 and $!{EINTR};   dIE $! if $? == -1;}exit( ( $? >> 8 ) | ( 0x80 | ( $? & 0x7F ) ) );
总结

以上是内存溢出为你收集整理的Perl从`system`命令转发SIGINT到父进程全部内容,希望文章能够帮你解决Perl从`system`命令转发SIGINT到父进程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1255560.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存