Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sleep in c [duplicate]

Tags:

c

sleep

Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string?

When I run something like

for (i = 1; i <= 10; i++) {
    sleep(1);
    printf(".");
}

then what I would expect is one dot per second ten times. What I get is ten dots once after ten seconds. Why is that so, and how do I get the program to actually print one point (or do other things) each second (or different time interval)?

like image 908
foaly Avatar asked Nov 14 '12 19:11

foaly


People also ask

Is there a sleep command in C?

The sleep() method in the C programming language allows you to wait for just a current thread for a set amount of time. The sleep() function will sleep the present executable for the time specified by the thread.

Which C library has sleep?

sleep() function is provided by unistd. h library which is a short cut of Unix standard library.

What does sleep () do in C ++?

The sleep() function shall cause the calling thread to be suspended from execution until either the number of realtime seconds specified by the argument seconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process.


1 Answers

The printf() is buffering the data, you can force it to flush that data with fflush(stdout):

for (i = 1; i<=10; i++) 
{  
    sleep(1); 
    printf("."); 
    fflush(stdout);
}
like image 74
Mike Avatar answered Sep 26 '22 23:09

Mike