在C语言中,可以使用sleep()
、usleep()
和nanosleep()
函数来产生延迟。下面是它们的用法示例:
#include <stdio.h>
#include <unistd.h> // 包含sleep()函数的头文件
#include <time.h> // 包含usleep()和nanosleep()函数的头文件
int main() {
printf("Sleeping for 5 seconds...\n");
sleep(5); // 延迟5秒
printf("Woke up!\n");
printf("Sleeping for 5000000 microseconds...\n");
usleep(5000000); // 延迟5秒(5000000微秒)
printf("Woke up!\n");
struct timespec ts;
ts.tv_sec = 5; // 延迟5秒
ts.tv_nsec = 0; // 纳秒部分设置为0
printf("Sleeping for 5 seconds...\n");
nanosleep(&ts, NULL); // 延迟5秒
printf("Woke up!\n");
return 0;
}
在这个示例中,我们使用了sleep()
、usleep()
和nanosleep()
函数来产生延迟。sleep()
函数接受秒数作为参数,usleep()
函数接受微秒数作为参数,而nanosleep()
函数接受时间结构体作为参数。在时间结构体中,可以使用tv_sec
和tv_nsec
字段分别设置秒和纳秒部分。在示例中,我们设置了5秒的延迟。