使用叉与C [英] Using fork with c
问题描述
这是一个学术问题如此的原因是理解输出。
It is an academic question so the reason is to understand the output.
我有一个code:
int main(int argc, char **argv) {
int k ;
while(*(++argv)) {
k = fork();
printf("%s ",*argv);
}
return 0;
}
结果
与运行程序:PROG A B结果
输出是:
running the program with : prog a b
The output is :
a b a b a b a b
为什么我得到这样的结果?
Why do I get this result?
推荐答案
由于在意见提出由克里斯·卢茨,你正在观察所使用的静态缓冲区的作用的printf
在叉()
呼叫被复制。由第一叉创建的两个过程()
不打印 B
如果(因为你能想到的,如发生强制刷新)。他们都打印 A B
因为它们都具有一个挂起,未刷新 A
在各自的缓冲器。
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.
有4个过程(2 ^ 2,包括最初的一个),它们都只有真正打印在出口时,缓冲区被刷新,并且它们都具有 AB
中当时他们各自的缓冲器。
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.
这篇关于使用叉与C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!