一連の子を生成するスクリプトがあります。親は、各子が終了するまで待つ必要があります。
私のスクリプトは、次の perl スクリプトと同様に実行されます。
#! /usr/bin/perl
use strict;
use warnings;
print "I am the only process.\n";
my @children_pids;
for my $count (1..10){
my $child_pid = fork();
if ($child_pid) { # If I have a child PID, then I must be the parent
push @children_pids, $child_pid;
}
else { # I am the child
my $wait_time = int(rand(30));
sleep $wait_time;
my $localtime = localtime;
print "Child: Some child exited at $localtime\n";
exit 0; # Exit the child
}
}
foreach my $child (@children_pids) {
print "Parent: Waiting on $child\n";
waitpid($child, 0);
my $localtime = localtime;
print "Parent: Child $child was reaped - $localtime.\n";
}
print "All done.\n";
上で提供したコードと同様に、それぞれの子が完了するまでに異なる時間がかかる場合があります。
問題は、子の PID をループして子を取得しようとすると、その最後のforeach
ブロックで、親が作成された順序で子を待機することです。
明らかに、子供たちは生成された順序で終了しないため、たまたま早期に終了する子供向けのゾンビプロセスがたくさん残っています。
私の実際のコードでは、これらの子プロセスが他のプロセスより数日早く終了する可能性があり、ゾンビ プロセスの数が数百単位で増加する可能性があります。
一連の子供たちを刈り取るためのより良い方法はありますか?