限制perl多进程数量

#!/usr/bin/perl
use strict;
use warnings;
use POSIX ":sys_wait_h";

my $maxproc = 4;
my $zombies = 0;
$SIG{CHLD} = sub { $zombies++ };
for my $item (1 .. 10)
{
        my $pid = fork();
        if (!defined $pid)
        {
        print "Error!\n";
                exit 1;
        }

        if ($pid == 0)
        {
                 print "child $item : my pid = $\n";
                 sleep 5;
                 print "child $item : end\n";
                 exit;
        }

        while (`ps -ef | grep $0 | wc -l` > $maxproc)
        {
            print "greate maxchild num\n";
            sleep 1;
        }

        if ($zombies > 0)
        {
            while ((my $collect = waitpid(-1, WNOHANG)) > 0)
                {
                    $zombies--;
                }
        }
}

你可能感兴趣的:(perl)