Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Here is my program.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello\n");
    system("uname");
    return 0;
}

Here is the output.

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

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

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

Why is the order of the output different when redirection is involved?

like image 758
Lone Learner Avatar asked Jan 03 '17 06:01

Lone Learner


People also ask

Can we redirect the output of a command to a file and display at the same time?

Redirecting output to Multiple files and screen: If you want to redirect the screen output to multiple files, the only thing you have to do is add the file names at the end of the tee command. We have provided you the syntax for this multiple file redirection.

How would you redirect output from stdout to a file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.

What command would you use to duplicate stdout from a program to both stdout and a file?

The tee command, used with a pipe, reads standard input, then writes the output of a program to standard output and simultaneously copies it into the specified file or files.

What is output redirection in C?

Before the C shell executes a command, it scans the command line for redirection characters. These special notations direct the shell to redirect input and output. You can redirect the standard input and output of a command with the following syntax statements: Item.


1 Answers

This is because stdout is buffered in different ways. When you call your program without the redirection, the buffering defaults to linewise buffering. In the second call, the buffer is much larger, and get written when your program terminates. Since your call to uname terminated before, this output now shows up earlier in the file. When you depend on the ordering, you can either explicit call fflush(stdout) after your printf call, or you can call uname via popen and print its output explicit.

like image 76
Rudi Avatar answered Sep 28 '22 03:09

Rudi