usleep() function does not allow a loop to continue

13,756

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

Share:
13,756
ggg
Author by

ggg

Updated on June 04, 2022

Comments

  • ggg
    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 ?