There are no sleep()
functions in the pre-C11 C Standard Library, but POSIX does provide a few options.
The POSIX function sleep()
(unistd.h) takes an unsigned int
argument for the number of seconds desired to sleep. Although this is not a Standard Library function, it is widely available, and glibc appears to support it even when compiling with stricter settings like --std=c11
.
The POSIX function nanosleep()
(time.h) takes two pointers to timespec
structures as arguments, and provides finer control over the sleep duration. The first argument specifies the delay duration. If the second argument is not a null pointer, it holds the time remaining if the call is interrupted by a signal handler.
Programs that use the nanosleep()
function may need to include a feature test macro in order to compile. The following code sample will not compile on my linux system without a feature test macro when I use a typical compiler invocation of gcc -std=c11 -Wall -Wextra -Wpedantic
.
POSIX once had a usleep()
function (unistd.h) that took a useconds_t
argument to specify sleep duration in microseconds. This function also required a feature test macro when used with strict compiler settings. Alas, usleep()
was made obsolete with POSIX.1-2001 and should no longer be used. It is recommended that nanosleep()
be used now instead of usleep()
.
#define _POSIX_C_SOURCE 199309L // feature test macro for nanosleep()
#include <stdio.h>
#include <unistd.h> // for sleep()
#include <time.h> // for nanosleep()
int main(void)
{
// use unsigned sleep(unsigned seconds)
puts("Wait 5 sec...");
sleep(5);
// use int nanosleep(const struct timespec *req, struct timespec *rem);
puts("Wait 2.5 sec...");
struct timespec ts = { .tv_sec = 2, // seconds to wait
.tv_nsec = 5e8 }; // additional nanoseconds
nanosleep(&ts, NULL);
puts("Bye");
return 0;
}
C11 does have the header threads.h
providing thrd_sleep()
, which works identically to nanosleep()
. GCC did not support threads.h
until 2018, with the release of glibc 2.28. It has been difficult in general to find implementations with support for threads.h
(Clang did not support it for a long time, but I'm not sure about the current state of affairs there). You will have to use this option with care.