tags:

views:

893

answers:

5

Is there a wait statement in c-component? for example, wait for 0.5 second before continuing the process?

thanks!

+7  A: 

In POSIX there is

usleep(500);

and

nanosleep(...);

have a look at the manual of usleep(3) and nanosleep(2). EDIT: nanosleep seems now to be the way to go, usleep is even deprecated in POSIX.2008 according to its manpage!

Johannes Weiß
+3  A: 

For Windows there is this function available in the API

Sleep(500);

Have a look at its MSDN page. It sleeps for the specified amount of milliseconds.

Johannes Schaub - litb
A: 

Thanks all. I appreciate your help!

Eric
please don't put personal comments in the answer fields. Instead comment on things or edit your original post.
Evan Teran
A: 

sleep is also available in POSIX, the difference is that argument specifies the number of Seconds instead of Milliseconds the process should sleep.

Note that using sleep() may not work as expected if you also use alarm().
Kristopher Johnson
+4  A: 

To summarize and correct a minor problem in Johannes Weiss' post (non-German keyboard, sorry):

In old-school POSIX, you could use the usleep() function, which accepts the number of microseconds to sleep as an unsigned integer argument. Thus, to sleep for half a second, you'd call:

#include <unistd.h>
usleep(500000); /* Five hundred thousand microseconds is half a second. */

For newer POSIX-style programs (my Gentoo Linux box' man pages says it's POSIX.1-2001), you'd use nanosleep(), which requires a pointer to a structure holding the period to sleep. Sleeping for half a second would look like this:

#include <time.h>
struct timespec t;
t.tv_sec = 0;
t.tv_nsec = 500000000; /* Five hundred million nanoseconds is half a second. */
nanosleep(&t, NULL); /* Ignore remainder. */

The second argument to nanosleep() is called "rem", and receives the remainder of the time, if the sleep is somehow interrupted. I left it at NULL for simplicity, here. You could do a loop until rem is (close enough to) zero, to make sure you really get your sleep, regardless of any interruptions.

unwind