问题描述
int main(void) {
printf("abc");
fork();
return 0;
}
这段代码的输出是:
abcabc
为什么会打印两次,即使 fork 系统调用在 printf 语句之后?
Why is it printing twice, even when fork system call is after the printf statement?
推荐答案
因为 stdout
是缓冲的,通常是行缓冲的.并且在您的程序中,缓冲区仅在 exit
时间或从 main
返回时刷新(当 fork
不这样做时,会发生两次"失败).
Because stdout
is buffered, often line-buffered. And in your program the buffer is flushed only at exit
time, or when returning from main
(and that happens "twice" when fork
don't fail).
尝试在 fork();
之前添加 fflush(NULL);
(您几乎应该总是这样做)
Try adding fflush(NULL);
before the fork();
(which you should almost always do)
顺便说一句,你应该始终保持fork
的结果并处理三种情况:fork
失败,在孩子,在父母.
BTW, you should always keep the result of fork
and handle three cases: fork
failure, in child, in parent.
所以 fork
表现得像它应该的那样,但是 printf
没有你想象的天真的直接副作用:它是 缓冲 所以真正的输出可能发生在后者.您还将通过将 fork()
替换为 sleep(15)
(输出发生在 exit
时间或结束时)来观察缓冲main
,所以 在 sleep
之后,并且在 15 秒内您的程序显然不会输出任何内容)
So fork
is behaving as it should, but printf
has not the naive immediate side-effect you imagine: it is buffering so the real output may happen latter. You'll also observe the buffering by replacing fork()
with sleep(15)
(the output happening at exit
time, or at end of main
, so after the sleep
, and for 15 seconds your program won't apparently output anything)
您也可以使用 strace(1)了解正在发生的系统调用...
You might also use strace(1) to understanding what system calls are happening...
这篇关于为什么 fork 系统调用的奇怪行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!