在Linux系统中,可以使用timerfd和clock_nanosleep这两个系统调用来实现精准的时间控制。下面分别介绍这两种方法:
timerfd:timerfd是Linux内核提供的一种定时器接口,可以用于创建一个文件描述符,该描述符会在指定的时间间隔产生事件。这里是一个简单的示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/timerfd.h>
#include <time.h>
int main() {
int timer_fd = timerfd_create(CLOCK_MONOTONIC, 0);
if (timer_fd == -1) {
perror("timerfd_create");
exit(EXIT_FAILURE);
}
struct itimerspec its;
its.it_value.tv_sec = 1; // 设置初始超时时间为1秒
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = 1; // 设置重复超时时间为1秒
its.it_interval.tv_nsec = 0;
if (timerfd_settime(timer_fd, 0, &its, NULL) == -1) {
perror("timerfd_settime");
exit(EXIT_FAILURE);
}
uint64_t expirations;
read(timer_fd, &expirations, sizeof(expirations));
printf("Timer expired %llu times\n", expirations);
close(timer_fd);
return 0;
}
编译并运行这个程序,你会看到每隔1秒,程序会输出"Timer expired X times",其中X是定时器触发的次数。
clock_nanosleep:clock_nanosleep函数可以让当前线程休眠指定的时间。这里是一个简单的示例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
struct timespec ts;
ts.tv_sec = 1; // 设置休眠时间为1秒
ts.tv_nsec = 0;
if (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == -1) {
perror("clock_nanosleep");
exit(EXIT_FAILURE);
}
printf("Slept for 1 second\n");
return 0;
}
编译并运行这个程序,你会看到程序会休眠1秒,然后输出"Slept for 1 second"。
这两种方法都可以实现精准的时间控制,具体选择哪种方法取决于你的需求。如果你需要在多个线程或进程之间同步时间,timerfd可能是更好的选择。而如果你只需要让当前线程休眠一段时间,clock_nanosleep可能更简单一些。