Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有以下代码:
for(i=1; i<=2; i++) { fork(); printf("x "); }
我计算出 x 应该打印 6 次:第一次迭代两次,第二次迭代 4 次。
相反,X 被打印了 8 次。为什么?
因为缓冲。通常,stdout是行缓冲的,所以
stdout
printf("x ");
不会立即将其写入"x "终端,而是写入输出缓冲区。这是在进程fork()s 时复制的,因此第二次迭代后的四个进程中的每一个"x "在输出缓冲区中都有两个 [一个来自父级/在第一次迭代中分叉之前,一个来自第二次迭代],并且八个xs 是完全印刷。
"x "
fork()
x
在 之后立即刷新缓冲区printf("x ");,只会打印六个。