次のコードは、10 秒間待機して終了する 2 つの子プロセスを実行します。親はループに座って、子が終了するのを待っています。
#!/usr/bin/perl
use strict;
use warnings;
use POSIX ":sys_wait_h";
sub func
# {{{
{
my $i = shift;
print "$i started\n";
$| = 1;
sleep(10);
print "$i finished\n";
}
# }}}
my $n = 2;
my @children_pids;
for (my $i = 0; $i < $n; $i++) {
if ((my $pid = fork()) == 0) {
func($i);
exit(0);
} else {
$children_pids[$i] = $pid;
}
}
my $stillWaiting;
do {
$stillWaiting = 0;
for (my $i = 0; $i < $n; ++$i) {
if ($children_pids[$i] > 0)
{
if (waitpid($children_pids[$i], WNOHANG) != 0) {
# Child is done
print "child done\n";
$children_pids[$i] = 0;
} else {
# Still waiting on this child
#print "waiting\n";
$stillWaiting = 1;
}
}
#Give up timeslice and prevent hard loop: this may not work on all flavors of Unix
sleep(0);
}
} while ($stillWaiting);
print "parent finished\n";
コードはこの回答に基づいています: Multiple fork() Concurrency
正しく動作しますが、親ループがプロセッサ時間を消費しています。top
コマンドはこれを与えます:
ここで答えは言う:
追加のボーナスとして、
waitpid
子が実行されている間はループがブロックされるため、待機中にビジー ループは必要ありません。
しかし、私にとってはブロックしません。どうしたの?