0

why my program NOT printf ?

First asleep and then writes , but he should do it the other way round..

#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

void sleepMilliSecond(long milliSecondInput) {
#ifdef _WIN32
    Sleep(milliSecondInput); // v milliSecondach
#else
    usleep(pollingDelay * 1000); //microsekundy -> milisekundy
#endif
}



int main(int argc, char** argv) {  
    printf("start sleep");    
    sleepMilliSecond(1000);   //sleep 1s 
    printf("stop sleep");
    return (EXIT_SUCCESS);
}

Output of program is: sleep and then he write start sleep stop sleep, WHY?

EDIT: Working solution is:

printf("start sleep");    
fflush(stdout);
sleepMilliSecond(10000); 
printf("stop sleep");
tilefrae
  • 133
  • 1
  • 2
  • 9

2 Answers2

6

printf is buffered I/O. To force the buffer to be written to output you can call fflush as so:

printf("start sleep");
fflush(stdout);
sleepMilliSecond(1000);   //sleep 1s 
printf("stop sleep");
SleuthEye
  • 13,074
  • 2
  • 28
  • 56
4

You are not flushing "stop sleep" and "start sleep" it's still in the buffer. Add a \n to the end:

printf("start sleep\n");
printf("stop sleep\n");

Luis Alves
  • 1,206
  • 12
  • 27