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

Understanding why fork gives different result in C

虽然有一些类似的问题比如this and this

我仍然无法理解为什么 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 之后,两个进程最终都会刷新缓冲区并将内容分别打印到屏幕上。

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

这是由于缓冲行为。

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

在你调用fork之前刷新输出,所以当它仍然只是一个进程时打印已经完成。

至于为什么 printf("Hello World\n"); 会立即刷新而 printf("Hello World"); 不会立即刷新,这并不容易。这取决于实际情况。在您的情况下,您可能 运行 它在行缓冲很常见的命令行中,行缓冲意味着一旦您获得换行符,它将被刷新。如果您写入文件,它可能会在您获得任何输出之前缓冲更多,并且在第一种情况下您也可能会看到 2 个输出。

如果您想要与冲洗保持一致的行为,您可能想自己做。

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

printf("Hello World")

printf("Hello World\n")

STDOUT是line buffered也就是说printf只会在缓冲区full[=35]时执行=] 或当它由 换行符 字符

终止时

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

因此,不同的响应是由于 Buffering 行为 stdout

希望对您有所帮助!!