gpt4 book ai didi

c - fork() 之前的 Printf 被打印两次

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:23 24 4
gpt4 key购买 nike

<分区>

我在使用 fork() 编写一个多进程程序时遇到了一个问题。

下面是重现问题的示例代码(没有任何类型的错误检查):

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main() {
printf("hello world");
fork();
}

此代码打印 2 个“hello world”语句(一个来自父级,另一个来自子级)。然而,情况并非如此,因为 printf 函数调用先于 fork() 系统调用。经过测试,问题似乎可以通过以下方式解决:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main() {
printf("hello world\n"); \\ addition of the new line character
// or by using fflush(stdout);
fork();
}

我的猜测是 printf 缓冲区在未刷新时被复制,因此子进程在退出之前清空了该缓冲区的副本。因此显示了其他 printf

谁能更好地解释这个问题?或者更好的是,如果我错了或遗漏了什么,请纠正我。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com