Question about sleep() function

Hello QNX gang!

I’m pretty new to this C++ high level language and QNX RTOS stuff and am curious why the sleep() function seems to delay the execution of ALL of the code, not just at the point where the sleep() call is located.

If you compile and run the following code you’ll observe that the first three cout functions that form the startup banner are not output until after the sleep timer elapses, which is not at all what I expected.


#include //~~~~ Required by cout function
#include <unistd.h> //~~~~ Required by sleep() function

using namespace std; //~~~~ Required by cout function

int main(int argc, char *argv[])

cout << “\n";
cout << "
This is a test of the sleep() function \n";
cout << "


cout << “\n";
cout << "
End of sleep() function test \n";
cout << "



I would greatly appreciate it if someone could clue me in as I’m a bit mystified right now.


Kevin Jackson

This is simple. You are sending to a buffered output stream. You send to stderr instead of stdout, or use fflush maybe.

[size=150][color=green]QNX Master Schoenbrun:

Thank you very much! :smiley:

Adding fflush(stdout) after the first three cout statements did the trick so those couts now happen BEFORE the sleep(10) as I had naively expected them to prior to your assistance.

Using fflush(stdout) also solved another phenomena I was seeing where issuing a read(stdin, &buf, 1) caused the application to wait for a character (plus Enter unfortunately) BEFORE sending out the prior cout statements.

Now if I can only figure out how to get unbuffered keyboard INPUT to work… :unamused:

Warmest Regards,

Kevin Jackson[/size]

I would suggest, instead of using fflush(stdout), using std::endl. endl will do the \n and fflush() for you. e.g:

cout << “A bunch of text.” << endl;

This has advantages and disadvantages. The biggest advantage is that this is the C++ solution to the problem. fflush() is ANSI, at least, but it’s still a C function call. People can argue about whether it’s easier to remember to put the endl and the extra “<<” in there or to put the fflush(). The endl solution takes one line less. And it’s what most C++ programmers will expect.

The main disadvantage is that endl isn’t exactly clear about what it’s doing, whereas fflush is pretty obvious. Of course, it’s not always obvious WHY you’re doing an fflush().

-James Ingraham
Sage Automation, Inc.

[size=150][color=olive]Thank you QNX Sage Ingraham!

I didn’t realize that endl was any different than ‘\n’. I’ll use endl from now on since I can’t see any benefit to having output buffering that adds unpredicatable delays to cout statements.

Best Regards,

Kevin Jackson[/size]