LinuxCommandLibrary
GitHubF-DroidGoogle Play Store

nanosleep

suspends execution of the calling thread for the specified duration

TLDR

Sleep for 1 second (C code)
$ struct timespec ts = {1, 0}; nanosleep(&ts, NULL);
copy
Sleep for 500 milliseconds
$ struct timespec ts = {0, 500000000L}; nanosleep(&ts, NULL);
copy
Sleep with remaining time
$ nanosleep(&req, &rem);
copy

SYNOPSIS

int nanosleep(const struct timespec *req, struct timespec *rem)

DESCRIPTION

nanosleep suspends execution of the calling thread for the specified duration. Unlike sleep(), it provides nanosecond precision and handles interruption gracefully.The function returns immediately if interrupted by a signal, storing remaining time in rem.

PARAMETERS

req

Requested sleep time (seconds and nanoseconds).
rem
Remaining time if interrupted (can be NULL).

EXAMPLE

$ #include <time.h>

int main() {
    struct timespec req = {0, 100000000L}; // 100ms
    struct timespec rem;

    while (nanosleep(&req, &rem) == -1) {
        req = rem; // Continue sleeping
    }
    return 0;
}
copy

TIMESPEC STRUCTURE

$ struct timespec {
    time_t tv_sec;   // Seconds
    long   tv_nsec;  // Nanoseconds (0-999999999)
};
copy

CAVEATS

Actual resolution depends on system clock. May sleep slightly longer than requested. EINTR on signal delivery.

HISTORY

nanosleep was introduced in POSIX.1-2001 to provide high-resolution sleep functionality beyond the second granularity of sleep().

SEE ALSO

sleep(3), usleep(3)

Braincup
Open source brain training for math, memory and focus
Braincup mini-games
41 mini-games · Apache-2.0
No ads · No tracking
Play in browser
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid
276 stars
From the maker of Linux Command Library
Copied to clipboard
Braincup
Open source brain training for math, memory and focus. 41 mini-games, from mental arithmetic to Sudoku, N-Back and Solo Chess.
Apache-2.0 licensed · No ads · No tracking · No account
From the maker of Linux Command Library
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid