为什么shell和文件之间的输出不同

sub*_*ash 4 c unix bash fork

考虑以下程序.

main() {  
  printf("hello\n");  
  if(fork()==0)  
    printf("world\n");  
  exit(0);  
}  
Run Code Online (Sandbox Code Playgroud)

使用./a.out以下输出编译此程序:

hello  
world 
Run Code Online (Sandbox Code Playgroud)

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

hello  
hello  
world 
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Yu *_*Hao 15

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

之后fork(),子进程将继承缓冲区,当你输出到shell时,缓冲区由于新行\n而为空,但是当你输出到文件时,缓冲区仍然包含内容,并且将同时包含在父级和子级中输出缓冲区,这hello就是看到两次的原因.

你可以这样试试:

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

hello输出到shell时你可能会看到两次.