c - 理解为什么 fork 在 C 中给出不同的结果

标签 c linux output fork

虽然有一些类似的问题,比如thisthis

我仍然无法理解为什么 fork 使用以下两个代码给出不同的输出

#include<stdio.h> 
void main()
{
    printf("Hello World\n");
    fork();
}

给出输出

Hello World

这段代码在哪里

#include<stdio.h> 
void main()
{
    printf("Hello World");
    fork();
}

给出输出

Hello WorldHello World

第二种情况我从其他问题中很清楚,两个进程都获得了同一个缓冲区的副本。因此,在 fork 之后,两个进程最终都会刷新缓冲区并将内容分别打印到屏幕上。

但是我不清楚为什么第一种情况会这样。

最佳答案

让我用简单的话来解释一下: 考虑一下,这两个语句:

printf("Hello World")

printf("Hello World\n")

STDOUT 是line bufferedprintf 仅当缓冲区已满 或被 终止时才执行>换行符字符

printf("Hello World") will not be guaranteed to display the output unless the

Buffer is full or terminated by new line character..Thus when a fork() is called,

Fork will create a copy of a process,this means that after fork, there are two identical processes,

each having a copy of the FILE* STDOUT Therefore, each process will have the same buffer contents of STDOUT

因为在你的第二个程序中没有换行符,

each process has the string in its buffer.

Then each process prints another string, and all of the contents are printed since it is terminated by a new line character. This is why you see two identical outputs.

但是

In your first program,there is a new line character and it displays output

immediately after the statement is executed and hence it flushes the contents of buffer..thus when a fork() is called

The process tries to access the buffer but since the buffer is empty,it does not print anything

因此,不同的响应是由于 stdoutBuffering 行为造成的

希望对您有所帮助!

关于c - 理解为什么 fork 在 C 中给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147037/

相关文章:

c - 如何从 c 调用回调 tcl 过程

c - 无法设置 Pthread 优先级

CMakeLists.txt 访问 GSL 库 C

ruby-on-rails - 具有基于 Web 的 UI/API 的 FTP 客户端/服务器

linux - vcan0接口(interface)linux通信

c - 我应该在我的代码中使用 register 关键字吗?

c - 这个 C 代码有什么漏洞? (整数...)

c++ - 如何反转 C++ 中的输出顺序? (有或没有递归)

java - 仅输入到终端的底行

java - 输入对话框[所需信息]