这是一个学术问题,所以理由是要理解输出。
我有一个代码:
int main(int argc, char **argv) { int k ; while(*(++argv)) { k = fork(); printf("%s ",*argv); } return 0; }运行程序:prog ab 输出是:
a b a b a b a b为什么我得到这个结果?
It is an academic question so the reason is to understand the output.
I have a code:
int main(int argc, char **argv) { int k ; while(*(++argv)) { k = fork(); printf("%s ",*argv); } return 0; }running the program with : prog a b The output is :
a b a b a b a bWhy do I get this result?
最满意答案
正如Chris Lutz在评论中所建议的那样,您正在观察由fork()调用复制的printf使用的静态缓冲区的效果。 由第一个fork()创建的两个进程不打印b (正如您所料,并且如果强制刷新则会发生)。 它们都打印ab因为它们在各自的缓冲区中都有待处理的未刷新的a 。
有4个进程(2 ^ 2,包括初始进程),它们只在刷新缓冲区时才真正在出口处打印,并且它们在那时都在各自的缓冲区中都有ab 。
As suggested by Chris Lutz in the comments, you are observing the effect of a static buffer used by printf being duplicated by the fork() call. The two processes created by the first fork() do not print b (as you could expect, and as happens if you force a flush). They both print a b because they both have a pending, unflushed a in their respective buffers.
There are 4 processes (2^2, including the initial one), they all only really print at exit when the buffer is flushed, and they all have a b in their respective buffers at that time.
更多推荐
发布评论