Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why output is different between to shell and to a file

Tags:

c

bash

fork

unix

Consider the following program.

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

Compiling this program using ./a.out gives the following Output:

hello  
world 

compiling this program using ./a.out > output gives the output in the file called 'output' and appears to be like this:

hello  
hello  
world 

Why is this so?

like image 436
subaash Avatar asked Dec 01 '22 18:12

subaash


2 Answers

Because when you output to shell stdout is usually line buffered, while when you write to a file, it's usually full buffered.

After fork(), the child process will inherit the buffer, when you output to shell, the buffer is empty because of the new line \n, but when you output to a file, the buffer still contains the content, and will be in both the parent and child's output buffer, that's why hello is seen twice.

You can try it like this:

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

You will likely see hello twice when output to shell as well.

like image 168
Yu Hao Avatar answered Dec 16 '22 05:12

Yu Hao


This answer after Yu Hao 's answer . He already explain a lot .

main() {  
  printf("hello\n");  
  fflush(stdout);//flush the buffer
  if(fork()==0)  
    printf("world\n");  
  exit(0);  
}  

Then you can get the right output.

like image 40
Lidong Guo Avatar answered Dec 16 '22 04:12

Lidong Guo