目录
函数介绍
具体细节可以参考文献
下图列出基本的函数使用介绍
测试代码
#include <stdio.h>
#include <unistd.h>
#include <sys/timerfd.h>
#include <fcntl.h>
#include <stdint.h>
int main()
{
// int timerfd_create(int clockid, int flags);
int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
if(timerfd < 0)
{
perror("timer_create error");
return -1;
}
// int timerfd_settime(int fd, int flags, struct itimerspec *new, struct itimerspec);
struct itimerspec itime;
itime.it_value.tv_sec = 1; // 设置 秒钟
itime.it_value.tv_nsec = 0; // 设置 纳秒 第一次超时时间为1s后
itime.it_interval.tv_sec = 1; // 同上
itime.it_interval.tv_nsec = 0;// 第一次超时后,每隔超时的间隔时
timerfd_settime(timerfd, 0, &itime, nullptr); // 0代表阻塞式
while (1)
{
uint64_t times;
int ret = read(timerfd, ×, 8);
if(ret < 0)
{
perror("read error");
return -1;
}
printf("超时了, 距离上一次超时了%ld次\n", times); // 要使用ld类型的去接收,因为times占8字节
}
close(timerfd); // 记得关闭描述符
return 0;
}
测试结果
符合预期