usleep() function does not allow a loop to continue
Solution 1
Your output buffer is not being flushed. By default, output is written when a new line appears in the stream. Change your printf
to this:
printf("%d\n", i);
or try this:
printf("%d", i);
fflush(stdout);
Also, if you want to remove the line-buffering behaviour, you can use setvbuf()
and the _IONBUF
mode.
Solution 2
Aside - To pass 1 sec to usleep
, call usleep(1000000)
Solution 3
call fflush(stdout)
after each printf to flush the buffered output
ggg
Updated on June 04, 2022Comments
-
ggg about 2 years
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { int i=0; while(i<10) { printf("%d", i); usleep(10000); // or sleep(1) i++; } return 0; }
I want the program to last 10 secs, i.e. print 1 - wait 1 sec - print 2 - wait 1 sec and so on until the end. But it doesn't do that - it just waits for all the time (10 secs) and then prints the whole array of numbers together without any time delays between them, it just prints 0123456789 at once. EDIT: I tried with sleep() instead of usleep but it's the same How to fix it ? And why it's like that ?