gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:57:32 26 4
gpt4 key购买 nike

虽然有一些类似的问题,比如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/

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