Suppose I have this situation: I redirected standard error of some program to the file output.err and standard output to the file output.out. When the program is run but killed before it is allowed to complete normally, I notice that the output.err file contains the expected output, but that output.out is empty even though I guarantee that the appropriate printf statements were executed. Why is this?
-
2stdout is buffered and stderr isn't so stderr hits the file when written, not at some point later. – Duck Apr 16 '14 at 17:06
2 Answers
This is because STDERR is never buffered. That means the data is written instantly no matter what. To flush the buffered data in STDOUT you can use this function:
some_write_operation_on_stdout();
fflush(stdout);
This call results in the data getting flushed from the buffer and written as if it were unbuffered. To disable buffering of STDOUT permanently you could just call this once:
setbuf(stdout, NULL);
See Why does printf not flush after the call unless a newline is in the format string? for more info.

- 1
- 1
That may be because the program uses a library for writing output that contains a buffer (as is typically the case for C's stdout
file stream), and the output isn't actually written to the device until that buffer is flushed (which doesn't happen when you kill the program). By contrast, C's stderr
is unbuffered. (Buffering can be controlled with setbuf()
.)

- 464,522
- 92
- 875
- 1,084