在终端上运行时以及当o/p重定向到文件时使用fork的代码的不同行为

abh*_*bhi 1 c linux fork

我遇到了一些测试代码,它直接在终端上执行时提供不同的输出,当它的输出重定向到文件时:

# include <stdio.h>
# include <stdlib.h>
int main()
{
     printf("hello\n");
     if(fork() ==0)
     {
            printf("world\n");
     }
}
Run Code Online (Sandbox Code Playgroud)

在终端上输出是:

abhi@ubuntu:~/Desktop/ad/A1/CC$ ./vb
hello
abhi@ubuntu:~/Desktop/ad/A1/CC$ world
Run Code Online (Sandbox Code Playgroud)

(打印世界后光标仍然闪烁,输入后显示正常提示.)

在将输出重定向到文件时:

./vb >v.txt
 abhi@ubuntu:~/Desktop/ad/A1/CC$ cat v.txt 
 hello
 hello
 world
Run Code Online (Sandbox Code Playgroud)

据我所知,父母不等孩子就打印hello并返回.然后孩子应该打印world,代码应该终止.

我无法理解的是,为什么代码在重定向输出时表现不同.这是什么原因?

cni*_*tar 8

当stdout被重定向到文件时,它不是行缓冲的.当它是tty时,它就是.因此,当写入tty时,printf立即写入stdout并且"这就是她所写的全部内容".

但是当stdout重定向到文件时"hello\n"仍保留在stdio缓冲区中.当你fork,两个进程(子进程和父进程)最终得到stdio缓冲区的副本,它们在退出时刷新.


偏离主题:在我看来o/p,写出"输出"真的是一种非常糟糕的方式 - 我讨厌用一千个太阳的白热强度.