#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?
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:
\n
) is to be printedstdin
fflush()
is called on itEDIT: 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With