>
> The following program doesn't "seem" to print "hello-out". What is
> the reason behind it??
>
> #include <stdio.h>
> #include <unistd.h>
> int main()
> {
> while(1)
> {
> fprintf(stdout,"hello-out");
> fprintf(stderr,"hello-err");
> sleep(1);
sleep(2) is not portable.
> }
> return 0;
> }
Yes it's true: the program doesn't "seem" to print "hello-out",
but it "does" print "hello-out". If you understand the concept
of buffering, you will come know to why the above program behaves
like this.
Streams are of two types: buffered and unbuffered. Buffered
streams are flushed when any of the following conditions are met:
* The buffer is full
* When '\n' is encounterd, if the stream is line buffered
* When a function to read from stdin is invoked
* When the program exits
* If the default flushing behaviour is modified by the
setvbuf(3) library function.
Whereas, unbufferd stream are flushed as soon as the data arrive.
stderr is unbuffered by default, because this stream is used for
error reporting, and error reporting should not be delayed by buffering.
Run the above program without change and see that after some time
"hello-out" is printed in bulk. stdout is line buffered, so if you
replace the above
fprintf(stdout,"hello-out");
with
fprintf(stdout,"hello-out\n");
"hello-out" is printed in iteration.