Why do I need to use fflush on stdout before writing to stderr?

I read "UNIX Network Programming: Sockets Network Interface", and in the sample code they have an error handling function that contains the following lines:

fflush(stdout); /* in case stdout and stderr are the same */ fputs(buf, stderr); fflush(stderr); 

Where buf contains a description of the error. I do not understand why fflush is used on stdout in the first line and why the comment explains the reason for using it.

+5
source share
2 answers

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.

+11
source

If stdout and stderr point to the same file, you must be sure that everything in the stdout buffer is written first.

+1
source

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


All Articles