Why doesn't this c program print the first printf statement?

#include<stdio.h> #include <unistd.h> int main(){ while(1) { fprintf(stdout,"hello-out"); fprintf(stderr,"hello-err"); sleep(1); } return 0; } 

When compiling this program in gcc and executing it, it only prints hi-err and does not greet. Why is this so? Can someone explain the reason for this?

+6
source share
3 answers

If you add the message '\n' to the message, it will (or should), i.e. "hello-out\n" .

The reason is that stdout buffered to be more efficient, while stderr does not buffer its output and is more suitable for error messages and things that need to be printed immediately.

stdout usually reset when:

  • Print a new line ( \n )
  • You read stdin is called on it
  • fflush()

EDIT:. Another thing I wanted to add before my computer crashed ... twice ... was that you can also use setbuf(stdout, NULL); to disable stdout buffering. I did this before when I had to use write() (Unix) and did not want my output to be buffered.

+17
source

It does not always output to stdout, because by default stdout has BUFFERED output, and stderr does not load. In general, for a buffered output stream, the stream is not flushed until the system is β€œfree” for this. Thus, data can continue buffering for a long time before it is flushed. If you want to force a fflush , you can do it manually 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 a linear buffer when connected to the terminal and simply buffers otherwise (e.g. redirection or channel)

+3
source

You forgot newlines (marked \n ) in your lines. Or you need to call fflush(NULL); or at least fflush(stdout); before sleep(1);

And fprintf(stdout, ...) matches printf(...)

You need to print new lines or call fflush , because (at least on Linux) the stdout FILE buffer is buffered by line. This means that the C library performs data buffering and actually outputs it (using the write Linux system call ) when the buffer is full enough, or when you clear it with either a new line or call fflush . Buffering is necessary because system calls are expensive (the write call for each byte to be output is really too slow). See also the setbuf man page .

+1
source

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


All Articles