谁先跑叉,结果相互矛盾

Who runs first in fork, with contradicting results

我有这个简单的测试:

int main() {
    int res = fork();
    if (res == 0) { // child
        printf("Son running now, pid = %d\n", getpid());
    }
    else { // parent
        printf("Parent running now, pid = %d\n", getpid());
        wait(NULL);
    }
    return 0;
}

当我运行它一百次,即运行这个命令,

for ((i=0;i<100;i++)); do echo ${i}:; ./test; done

我得到:

0:
Parent running now, pid = 1775
Son running now, pid = 1776
1:
Parent running now, pid = 1777
Son running now, pid = 1778
2:
Parent running now, pid = 1779
Son running now, pid = 1780

等等;而当我第一次写入文件并 然后 读取文件时,即 运行 这个命令,

for ((i=0;i<100;i++)); do echo ${i}:; ./test; done > forout
cat forout

我明白了!也就是说,

0:
Son running now, pid = 1776
Parent running now, pid = 1775
1:
Son running now, pid = 1778
Parent running now, pid = 1777
2:
Son running now, pid = 1780
Parent running now, pid = 1779

我知道调度程序。就分叉后谁先 运行 而言,这个结果不意味着什么? 分叉函数 do_fork()(在 kernel/fork.c)以将 need_resched 标志设置为 1 结束,内核开发人员评论说 "let the child process run first."

我猜想这与 printf 写入的缓冲区有关。

此外,输入重​​定向 (>) 是先将所有内容写入缓冲区,然后再复制到文件,这样说对吗?即便如此,为什么这会改变打印的顺序?

注意:我正在运行测试单核虚拟机Linux 内核 v2.4.14.

感谢您的宝贵时间。

当您重定向时,glibc 检测到 stdout 不是 tty 打开输出缓冲以提高效率。因此,在进程退出之前不会写入缓冲区。你可以看到这个,例如:

int main() {
  printf("hello world\n");
  sleep(60);
}

当您 运行 交互时,它会打印 "hello world" 并等待。当你重定向到一个文件时,你会看到 60 秒内没有写入任何内容:

$ ./foo > file & tail -f file
(no output for 60 seconds)

由于您的父进程等待子进程,它必然总是最后退出,因此最后刷新其输出。