【问题标题】:Perl forward SIGINT to parent process from `system` commandPerl 从 `system` 命令将 SIGINT 转发到父进程
【发布时间】:2016-03-31 04:52:58
【问题描述】:

如果我有一个像apt-cache search <some query> 这样长时间运行的system 命令,有没有办法将命令行上通过^C 发送的SIGINT 转发到父Perl 进程,这样所有子进程进程被收割。

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

#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';
use autodie;

# long running command on ubuntu, produces a ton of output.
# replace with your favorite long running command
system("apt-cache search hi");

print("Perl did not catch SIGINT even with autodie\n");

我尝试四处寻找捕获将由system("apt-cache search hi &") 创建的孩子的pid 的方法,但找不到任何方法,所以我尝试forking 和execing 进程并编写信号处理程序。这不起作用,因为apt-cache 本身通过clone 系统调用启动了一些进程。手动滚动一些逻辑来遍历部分流程树并清理

#!/usr/bin/env perl
use 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";

我想基本上我想要的是一种确定system 启动的子进程是否由于SIGINT 之类的信号而退出的方法,这样我就可以让 Perl 脚本自行清理,或者是一种行走的方法子进程并以这样的方式收获它们,从而干净且可移植地处理奇怪的进程管理边缘情况。

【问题讨论】:

标签: perl


【解决方案1】:

让孩子成为一个进程组的负责人,然后将信号发送给整个进程组。

#!/usr/bin/perl

use 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', 'search', 'hi';
}

WAIT: {
   no autodie;
   waitpid($child_pid, 0);
   redo WAIT if $? == -1 and $!{EINTR};
   die $! if $? == -1;
}

exit( ( $? >> 8 ) | ( 0x80 | ( $? & 0x7F ) ) );

【讨论】:

  • kill INT => -$child_pid if $child_pid; 这是特定于 Windows 的吗?
  • 不,恰恰相反。 Windows 没有 POSIX 信号或进程组(尽管 kill 可用于向控制台应用程序发送 Windows 确实有的极少数信号之一,Ctrl-C 和 Ctrl-Break)。
  • 那么否定 cpid 有什么作用呢?
  • $cpid标识的进程组中的每个进程发送信号
猜你喜欢
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2011-11-04
相关资源
最近更新 更多