当我在循环中包含 fork()
函数调用时,循环执行的次数超过预期。为了简单起见,我只选择了两次迭代;你可以用更多的东西来测试。
我试过设置autoflush on
,但这似乎不起作用。
use strict;
use warnings;
use IO::Handle;
$|++; #autoflush on
STDOUT->flush();
for my $i (1 .. 2) {
print "Normal => $i\n";
}
print "\n";
for my $i (1 .. 2) {
my $pid = fork();
if(not defined($pid)) {
die "cannot fork\n";
} elsif (not $pid) {
print "Child => $i\n";
} else {
print "Parent => $i\n";
wait();
}
}
实际输出
Normal => 1
Normal => 2
Parent => 1
Child => 1
Parent => 2
Child => 2
Parent => 2
Child => 2
预期输出
Normal => 1
Normal => 2
Parent => 1
Child => 1
Parent => 2
Child => 2
请帮助我了解这里出了什么问题。
最佳答案
您最终调用 fork()
三次,总共 四个 进程。
这是一种可能的执行顺序,它会产生您看到的输出:
Process 1 Process 2 Process 3 Process 4
$i == 1
fork----------->$i == 1
"Parent 1"
"Child 1"
$i == 2
fork--------------------------->$i == 2
"Parent 2"
"Child 2"
$i == 2
fork--------------------------->$i == 2
"Parent 2"
"Child 2"
wait
reaped
zombie zombie
关于perl - 为什么包含 fork() 调用会产生更多循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55488363/