gpt4 book ai didi

c - 为什么 shell 和文件的输出不同

转载 作者:太空狗 更新时间:2023-10-29 15:11:17 25 4
gpt4 key购买 nike

考虑以下程序。

main() {  
printf("hello\n");
if(fork()==0)
printf("world\n");
exit(0);
}

使用 ./a.out 编译该程序会得到以下输出:

hello  
world

使用 ./a.out > output 编译这个程序会在名为“output”的文件中给出输出,看起来像这样:

hello  
hello
world

为什么会这样?

最佳答案

因为当您输出到 shell stdout 时通常是行缓冲的,而当您写入文件时,它通常是全缓冲的。

fork()之后,子进程会继承buffer,当你输出到shell时,因为换行\n,buffer是空的,但是当你输出到一个文件,缓冲区仍然包含内容,并且将在父项和子项的输出缓冲区中,这就是 hello 被看到两次的原因。

你可以这样试试:

int main() {  
printf("hello"); //Notice here without "\n"
if(fork()==0)
printf("world\n");
exit(0);
}

当输出到 shell 时,您可能会看到两次 hello

关于c - 为什么 shell 和文件的输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18033220/

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