Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

30
Mar

Stream buffering

Related Blog Items

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);
    }
    return 0;
}

When you observe, it looks as if the program prints only "hello-err".
But then, all of sudden, it prints "hello-out" in a bulk!  Why the
program should behave like that when it should print "hello-out" and
"hello-err" in sequence?

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.  Streams also can
also be categorized as text streams and binary streams.  However, on a
system like UNIX, these are identical.  Text streams that are buffered
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.

To know more on streams, refer K&R-II, section B.1.

Popularity: 6%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image