Why is the order of the C program output different when its stdout is redirected to a file?

Here is my program.

#include <stdio.h> #include <stdlib.h> int main() { printf("Hello\n"); system("uname"); return 0; } 

Here is the result.

 $ gcc foo.c $ ./a.out Hello Linux 

However, if I redirect the output of the program to a file, I see that the output order is reverse, i.e. Linux prints before Hello .

 $ ./a.out > out.txt $ cat out.txt Linux Hello 

Why is the output order different when redirecting?

+6
source share
2 answers

This is because stdout is buffered in different ways. When you invoke your program without redirection, buffering is by default used for line buffering. In the second call, the buffer is much larger and is written when your program exits. Since your uname call completed earlier, this output is now displayed earlier in the file. When you depend on the order, you can either explicitly call fflush(stdout) after your call to printf , or you can call uname via popen and print your output explicitly.

+3
source

Since buffering is done on the terminal, the output order may vary.

+2
source

Source: https://habr.com/ru/post/1013716/


All Articles