在信号处理函数(Perl)中从main ::更新数组

0 arrays perl sigchld

我想维护一个我分叉的子项的pidlist数组,然后在它们退出时将它们删除(以限制我在任何给定时间有多少分叉进程).我认为我可能很聪明并且通过在删除或拼接中使用@main :: pid_list来做到这一点,但没有快乐.我可以成功弹出一个元素,但显然它不会删除正确的pid.任何想法如何处理这个或我会更好地做一些完全不同的方式?

#!/usr/bin/perl -w
use POSIX ":sys_wait_h";
use Data::Dumper;

# Only allow 5 processes running at a time

sub REAPER {
    my $child = shift;
    while (($child = waitpid(-1, WNOHANG)) > 0) {
        # Need to remove child from pidlist here
        #pop(@main::pid_list);                     #This works
        #delete($main::pid_list[$child]);          #This does not

    }
    $SIG{CHLD} = \&REAPER;
}

@pid_list = ();
@files = (1 .. 20);

foreach my $file (@files) {
    my $processed = 'false';
    while ($processed eq 'false') {

        print "Working on file: $file\n";
        $SIG{CHLD} = \&REAPER;
        if (scalar(@pid_list) < 5) {
            $pid = fork();
            if ( $pid == 0 ) {
                print "$$: Child Processing file #" . $file . "\n";
                sleep(10);
                print "$$: Child done processing file #" . $file . "\n";
                exit(0);
            }
            push(@pid_list, $pid);
            print Dumper(@pid_list);
            $processed = 'true';
        }
        sleep(1);
    }
}

# Since we are at the end we need to wait for the last process to end
print "PID: $$ End of parent program\n";

exit 0;
Run Code Online (Sandbox Code Playgroud)

soc*_*pet 5

使用哈希表而不是数组.

sub REAPER {
    my $child = shift;
    while (($child = waitpid(-1, WNOHANG)) > 0) {
        # Need to remove child from pidlist here
        delete $main::pid_list{$child};
    }
    $SIG{CHLD} = \&REAPER;
}

...

if ((scalar keys %main::pid_list) < 5) {
    ...
    if ($pid != 0) {
        ...
       exit(0);
    }
    $main::pid_list{$pid}++;
}
Run Code Online (Sandbox Code Playgroud)