Perl 分叉然后停止来自父进程的多个子进程

Perl forking then stopping multiple child processes from parent

在这种情况下,我需要我的 perl 程序启动多个持续时间未知的子进程,实际上只有父进程知道子进程何时需要结束。我一直在尝试分叉多个进程,然后从父进程中结束它,但没有成功。我目前拥有的:

成功fork掉一个进程然后结束

my $pid = fork();

if($pid == 0){
    #do things in child process
}

else{
    #examine external conditions, when the time is right:
    kill 1, $pid;
}

尝试将其扩展到 2 个进程失败:

my $pid = fork();

if($pid != 0){ #parent makes another fork
    my $pid2 = fork();
}

if($pid == 0 || $pid2 = 0){
    #do things in child process
}

else{
    #examine external conditions, when the time is right:
    kill 1, $pid;
    kill 2, $pid;
}

我已经阅读了互联网上所有关于 fork 的文档,它们都是关于分叉一个我理解得很好的进程的,但是我不知道如何将它扩展到 2 个或更多进程,如果您能就如何做到这一点提供任何帮助,我们将不胜感激。

遵循这段代码,我希望代码是不言自明的:

my $num_process = 5; ## for as many you want, I tested with 5
my %processes; ## to store the list of children

for ( 1 .. $num_process ) {

    my $pid = fork();

    if ( not defined $pid ) {
        die "Could not fork";
    }
    elseif ( $pid > 0 ) {
        ## boss
        $processes{$pid} = 1;
    }
    else {
        #do things in child process

        ## exit for child, dont forget this
        exit;
    }
}

## when things are right to kill ;-)
foreach my $pid ( keys %processes ) {
    kill 1, $pid;
}

一旦您很好地理解了第一个答案中发生的事情(但仅此而已!),请查看 Parallel::ForkManager(或类似内容)以了解实际工作。在处理子进程时,您可能会出错的小细节有很多,因此使用第三方模块可以节省很多时间。