Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't this c programme print the first printf statement?

Tags:

c

printf

#include<stdio.h>
#include <unistd.h>
int main(){
      while(1)
      {

              fprintf(stdout,"hello-out");
              fprintf(stderr,"hello-err");
              sleep(1);
      }
      return 0;
}

On compiling this programme in gcc and on executing it only prints hello-err and not hello-out.Why is that so?Can someone please explain the reason behind it?

like image 539
bornfree Avatar asked Nov 09 '11 06:11

bornfree


2 Answers

If you add a '\n' to your message it will (or should), ie. "hello-out\n".

The reason being is that stdout is buffered in order to be more efficient, whereas stderr doesn't buffer it's output and is more appropriate for error messages and things that need to be printed immediately.

stdout will usually be flushed when:

  • A newline (\n) is to be printed
  • You read in from stdin
  • fflush() is called on it

EDIT: The other thing I wanted to add before my computer crashed...twice...was that you can also use setbuf(stdout, NULL); to disable buffering of stdout. I've done that before when I've had to use write() (Unix) and didn't want my output to be buffered.

like image 82
AusCBloke Avatar answered Sep 27 '22 23:09

AusCBloke


It doesn't always print out the output to stdout because by design stdout is BUFFERED output, and stderr is unbuffered. In general, the for a buffered output stream, the stream is not dumped until the system is "free" to do so. So data can continue buffering for a long while, before it gets flushed. If you want to force the buffer to flush you can do so by hand using fflush

#include<stdio.h>
#include <unistd.h>
int main(){
      while(1)
      {

              fprintf(stdout,"hello-out");
              fflush(stdout); /* force flush */
              fprintf(stderr,"hello-err");
              sleep(1);
      }
      return 0;
}

Update: stdout is linebuffered when connected to a terminal, and simply buffered otherwise (e.g. a redirect or a pipe)

like image 44
Ahmed Masud Avatar answered Sep 27 '22 23:09

Ahmed Masud