0
#include <stdlib.h>

int main()
{
    printf("\nHello");
    sleep(5);
    printf("\nLinux");
}

In my expectation, It should be like:

PRINT Hello --- WAIT 5 SECS ---> PRINT Linux

But actually it will be like this:

WAIT 5 SECS --> PRINT Hello --> PRINT Linux

Why ? How to make my program be the first one (as my expectation) ?

And why my code can run expectedly on Win32 Console?

Kevin Dong
  • 5,001
  • 9
  • 29
  • 62

2 Answers2

4

Your stream is line-buffered, as you don't end your string with \n, flush it using fflush.

Change your program to:

int main()
{
    printf("\nHello");
    fflush(stdout);
    sleep(5);
    printf("\nLinux");
}
ouah
  • 142,963
  • 15
  • 272
  • 331
  • Wow, it works now, but why my code can run expectedly on Win32 Console? Microsoft problem? – Kevin Dong Jan 29 '14 at 09:52
  • 1
    @KevinDongNaiJia if the stream is fully buffered it will work without the `fflush` if it is line-buffered you'll need the `fflush`. Use `fflush` to have the same behavior on different configurations. – ouah Jan 29 '14 at 10:17
1

The output is buffered and is not printed until newline.

Try with:

printf("\nHello\n");
sleep(5);
printf("Linux");
fede1024
  • 3,099
  • 18
  • 23