0

I am having problems with the sleep() function not working. For example:

#include <stdlib.h>
#include <stdio.h>

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

     printf("\nHello!");
     sleep(1);
     printf("\nBye!");
     sleep(1);

     return 0;
}

Even simple programs like this won't work. It will sleep for 2 seconds then say "Hello! Bye!" and end the program. If anyone has any ideas they are appreciated!

user2864740
  • 60,010
  • 15
  • 145
  • 220
DarkSun
  • 41
  • 2
  • 6

2 Answers2

3

Output to stdout is buffered until a newline. [The newline immediately preceding the printf should flush, but the following characters will be buffered until a newline or explicit flush is forced {re: greg h}]

To flush stdout, call fflush( stdout )

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

    printf("\nHello!");
    // flush stdout
    fflush( stdout );
    sleep(1);
    printf("\nBye!");
    // flush stdout
    fflush( stdout );
    sleep(1);

    return 0;
}
polarysekt
  • 562
  • 1
  • 5
  • 17
  • could you give an example? I am 14 and just learning the language sorry if im a little slow – DarkSun Jul 28 '14 at 23:03
  • The `printf` statements *do* contain newlines, just in an unusual place... – Greg Hewgill Jul 28 '14 at 23:04
  • @Greg Hewgill printf does not contain newlines.. you have to put an escape character, but it doesn't flush automatically without it. – James Jul 28 '14 at 23:06
  • 1
    @James: No, really, there are newlines at the *start* of the output in the code in the question. – Greg Hewgill Jul 28 '14 at 23:06
  • haha, touche... the newlines would force a flush, but the following characters would be buffered. I updated my answer to include an example, and I will change my wording somewhat – polarysekt Jul 28 '14 at 23:07
1

By default, printf output is flushed (actually sent to the terminal) when a \n character is printed. So you can make your code work as follows:

 printf("Hello!\n");
 sleep(1);
 printf("Bye!\n");
 sleep(1);

In this case, I have moved the newline \n to the end of the string you are printing, instead of the beginning.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285