Perl分叉然后从父级停止多个子进程

时间:2015-09-21 14:16:14

标签: perl fork

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

成功分离一个流程然后结束它

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个或更多个进程,并且感谢任何有关如何做到这一点的帮助。

2 个答案:

答案 0 :(得分:3)

一旦你完全理解了第一个答案中的内容(但只有这样!),请查看Parallel::ForkManager(或类似内容)以获得实际工作。在使用子进程时,您可能会遇到很多很多小的琐碎细节,因此使用第三方模块可以节省大量时间。

答案 1 :(得分:0)

遵循此代码,我希望代码是自我解释的:

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;
}
相关问题