在C语言中,nanosleep()函数用于将当前线程挂起一段指定的时间。
nanosleep()函数的原型如下:
int nanosleep(const struct timespec *req, struct timespec *rem);参数说明:
req:一个指向结构体timespec的指针,用于指定挂起的时间。该结构体有两个成员:tv_sec表示秒数,tv_nsec表示纳秒数。rem:一个指向结构体timespec的指针,用于获取剩余的时间。如果指定的时间被完全阻塞,则该参数为0;如果指定的时间被部分阻塞,则该参数返回剩余的时间。返回值:
如果函数成功,则返回0;如果函数被信号中断,则返回-1,并且设置errno为EINTR;如果函数失败,则返回-1,并且设置errno为EINVAL。示例用法:
#include <stdio.h>#include <time.h>int main() { struct timespec req, rem; req.tv_sec = 2; // 设置挂起时间为2秒 req.tv_nsec = 500000000; // 设置挂起时间为500毫秒 int result = nanosleep(&req, &rem); if (result == -1) { printf("nanosleep failed\n"); return 1; } printf("Slept for %ld seconds and %ld nanoseconds\n", req.tv_sec - rem.tv_sec, req.tv_nsec - rem.tv_nsec); return 0;}在上述示例中,nanosleep()函数被用来挂起当前线程2.5秒。在函数调用后,程序会打印出实际挂起的时间。

