[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Buggy sleep()

From: Bob Proulx
Subject: Re: Buggy sleep()
Date: Thu, 5 Apr 2001 01:09:51 -0600

> I have noticed very strange bahaviour of sleep() function.
> Here are two examples:
> /* Ex1 */
> printf("something1");
> /* Ex2 */
> printf("something1\n");

> Could you please expalin me the differences between given examples,
> except new lines \n in printf().  The "bug" is that in Ex1 both
> strings are printed AFTER the sleep time.  The examples were
> compiled and tested under Slackware 7.1 gcc-2.95.2

Thanks for your report.  But fortunately for us that is not a bug but
the desired functionality.

The C standard I/O library has a behavior which frequently confuses
people new to it.  It decides when the program starts up if it should
buffer the output up and send it in big chunks for speed or not and if
so how much.  Normally if the output is a terminal then the standard
output is line buffered.  Output is saved up until a newline is seen
and then the larger chunk is written.  If it were a file instead then
it would buffer up to a big block size, perhaps a 1k byte chunk,
regardless of newlines.  Also, if the output is a terminal and any
input is done such as fgets() then all line buffered output is

The stderr stream is different and usually unbuffered if the device is
a terminal.  Unbuffered output is probably what you expected.  If you
were fprintf'ing to stderr then you would have seen the output
separately before and after the sleep().  As you can see that behavior
has nothing to do with sleep.  It is all part of standard I/O
buffering.  Standard I/O buffering is turned on and off automatically
depending on whether the output device is a terminal or not.

This is all described in, I think, chapter 7 of K&R.  But I don't have
my copy with me and I can't remember if the second edition was
organized differently or not so I might have that wrong.  Any book on
C programming should describe stdio in detail.

Also, in your program you were using printf but including <unistd.h>
instead of <stdio.h>.  For printf() <stdio.h> is the one you wanted.

Also, you are confusing the C standard library sleep() call in your
program with the shell command sleep from the sh-utils package.  They
are not related.  Except that the sh-utils sleep program calls the C
library sleep() function just like your program does.  If this were a
real bug in sleep() I would redirect you to the glibc mailing list at
address@hidden which might be useful for future reference.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]