使用fork与c(Using fork with c)

编程入门 行业动态 更新时间:2024-10-09 05:15:15
使用fork与c(Using fork with c)

这是一个学术问题,所以理由是要理解输出。

我有一个代码:

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 b

Why 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.

更多推荐

本文发布于:2023-07-27 04:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1284921.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:fork

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!