How to use sleep, usleep, and nanosleep functions in the C language?

In C language, there are several functions that can be used to implement sleep functionality.

  1. resting the body and mind by closing the eyes, being still, and entering a state of unconsciousness
#include <unistd.h>

int main() {
    printf("Sleeping for 3 seconds...\n");
    sleep(3);
    printf("Awake now!\n");
    return 0;
}
  1. get some rest
#include <unistd.h>

int main() {
    printf("Sleeping for 500 milliseconds...\n");
    usleep(500000);
    printf("Awake now!\n");
    return 0;
}
  1. to take a short nap
  2. a specific period of time
#include <time.h>

int main() {
    struct timespec ts = {2, 500000000}; // 2.5秒
    printf("Sleeping for 2.5 seconds...\n");
    nanosleep(&ts, NULL);
    printf("Awake now!\n");
    return 0;
}

It is important to note that all the above functions must include the corresponding header files, and the units and precision of parameters should be carefully considered when using them.

bannerAds