Kaunteya
Kaunteya

Reputation: 3090

Weird behaviour of stderr

I have this code in my program

while(1){
  // some code here

 fprintf(stdout,"Output Log");
 fprintf(stderr,"Error Log");


 //some code here
      }

It prints only "Error Log". It looked like I was missing to flush between two fprintf. Hence I appended "\n" to String "Output log". Worked fine. But cannot understand this weird behavior when I just swapped two fprintf

while(1){
  // some code here
 fprintf(stderr,"Error Log\n");
 fprintf(stdout,"Output Log");    

 //some code here
      }

Inspite of using "\n" it only prints "Error log".

Upvotes: 0

Views: 247

Answers (3)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215259

Your mistake is assuming that a newline "between" the two messages is what's causing both to appear. It's actually the newline at the end of the output to stdout which is causing the message to stdout to appear (the message to stderr is always visible because stderr is unbuffered).

In any case, relying on newlines to flush the buffer is unreliable unless you manually set line-buffered mode on stdout; line-buffered is only the default when stdout is a terminal. If you don't want to force line-buffered or unbuffered mode, then you must use fflush to get reliable interleaving of output to stdout and stderr.

Upvotes: 5

Mark Ransom
Mark Ransom

Reputation: 308206

It appears stdout is buffered and stderr is not. Since the program never ends, the buffer is never flushed.

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124642

stderr is special. It is never fully buffered at application start like stdout may be. It is implementation dependent as to whether or not it is line buffered, and it may not buffered at all (as it seems here).

It makes no difference if they are tethered to the same output device. This makes sense when you think about it; you probably want your errors to be flushed as quickly as is reasonable.

Upvotes: 1

Related Questions