C语言nanosleep函数的用法是什么
C语言中的nanosleep函数用于将程序的执行暂停一段指定的时间。
nanosleep函数的原型如下:
int nanosleep(const struct timespec *req, struct timespec *rem);
参数说明:
- req:指定程序要暂停的时间,以秒和纳秒为单位。它是一个timespec结构体,包含以下两个成员:
- tv_sec:指定要暂停的秒数。
- tv_nsec:指定要暂停的纳秒数。
- rem:如果函数在指定的时间内被信号中断,则会将剩余的时间存储在rem中。它也是一个timespec结构体。
函数返回值:
- 如果函数成功完成,则返回0。
- 如果函数被信号中断,则返回-1,并把剩余的时间存储在rem中。
nanosleep函数使用示例:
#include <time.h>
#include <stdio.h>
int main() {
struct timespec req, rem;
req.tv_sec = 2; // 暂停2秒
req.tv_nsec = 0;
if (nanosleep(&req, &rem) == -1) {
printf("nanosleep failed\n");
return 1;
}
printf("Sleep complete\n");
return 0;
}
上述示例中,程序将会暂停2秒钟。如果nanosleep函数被信号中断,将会打印"nanosleep failed",否则打印"Sleep complete"。