代码:
printf("hello\n"); //fflush(stdout); fork();
输出:
hello
代码:
printf("hello\n"); fflush(stdout); fork();
输出:
hello
hello
说明:系统函数fork()创建新的进程。
printh后打印内容在缓冲区里,fork后,父子进程的缓冲区里也是相同的,进程退出时,缓冲区输出到屏幕,所以有两份。
而fflush(stdout)当然是清空stdout的缓冲区了
本文探讨了在C语言中使用fork函数创建新进程前后,printf和fflush函数对输出缓冲区的影响。通过两个示例代码的对比,揭示了在没有使用fflush清空缓冲区的情况下,fork会导致子进程继承父进程未刷新的输出缓冲区内容,从而产生重复输出的现象。
代码:
printf("hello\n"); //fflush(stdout); fork();
输出:
hello
代码:
printf("hello\n"); fflush(stdout); fork();
输出:
hello
hello
说明:系统函数fork()创建新的进程。
printh后打印内容在缓冲区里,fork后,父子进程的缓冲区里也是相同的,进程退出时,缓冲区输出到屏幕,所以有两份。
而fflush(stdout)当然是清空stdout的缓冲区了
1358
1275
2959

被折叠的 条评论
为什么被折叠?