以下代码运行 2 个孩子,他们将等待 10 秒并终止。父母坐在一个循环中,等待孩子终止:
#!/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
孩子运行时阻塞,因此您在等待时不需要繁忙的循环。
但对我来说,它不会阻塞。怎么了?