This is due to buffering. Stdout and stderr are usually buffered differently . Stdout is usually a string buffer, that is, it will not display output until it sees a new line. Stderr is usually not buffered and printed immediately, thinking you should see pronto error messages.
But they both go there, the terminal. This is what /* in case stdout and stderr are the same */ means. They are usually. But since they are buffered in different ways, this can lead to them being displayed out of order.
Consider this code. Note the lack of new lines.
#include <stdio.h> int main() { fprintf(stdout, "This is to stdout. "); fprintf(stderr, "This is to stderr. "); fprintf(stdout, "This is also to stdout. "); }
You expect the output to be as follows:
This is to stdout. This is to stderr. This is also to stdout.
But this is not so. This is not in order.
$ ./test This is to stderr. This is to stdout. This is also to stdout.
The output to stderr is displayed immediately, it does not load. While stdout must wait until the stdout buffer is flushed with a new line. There is no new line, so it is reset when you exit the program.
By resetting stdout before you use stderr, you will make sure that the output comes in the correct order regardless of buffering.
#include <stdio.h> #include <unistd.h> int main() { fprintf(stdout, "This is to stdout. "); fflush(stdout); fprintf(stderr, "This is to stderr. "); fprintf(stdout, "This is also to stdout. "); } $ ./test This is to stdout. This is to stderr. This is also to stdout.
This ensures that error messages appear in the correct order with regular messages. This avoids confusion as to which error message relates to which part of the program.