#include
#include
int main(){
while(1)
{
fprintf(stdout,\"hello-out\");
fprintf(stderr,\"hel
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)
You forgot newlines (noted \n
) in your strings. Or you need to call fflush(NULL);
or at least fflush(stdout);
before sleep(1);
And fprintf(stdout, ...)
is the same as printf(...)
You need to output newlines or to call fflush
because (at least on Linux) the stdout
FILE buffer is line-buffered. This means that the C library is buffering data, and will really output it (using the write Linux system call) when the buffer is full enough, or when you flush it either with a new line, or by calling fflush
. Buffering is needed because system calls are costly (calling write
for every byte to be output is really too slow). Read also the man page of setbuf
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.