Linux timerfd 的基本使用

timerfd 是什么

timerfd 是一个时间相关的 fd,当 timerfd 初始化时,可以设置一个超时时间,超时之后,该句柄可读,读出来的是超时的次数。

timerfd 使用起来比较简单,我们把他的用法过一遍即可:

timerfd 的使用

timerfd 相关的系统调用有 3 个:

cpp 复制代码
// 创建一个 timerfd 句柄
int timerfd_create(int clockid, int flags);
// 启动或关闭 timerfd 对应的定时器
int timerfd_settime(int fd, int flags, const struct itimerspec *new_value, struct itimerspec *old_value);
// 获取指定 timerfd 距离下一次超时还剩的时间
int timerfd_gettime(int fd, struct itimerspec *curr_value);

timerfd 常与 epoll 系统调用结合使用:

cpp 复制代码
// 创建一个 timerfd 句柄
int fdTimer = timerfd_create(CLOCK_MONOTONIC, 0 /*flags*/);

itimerspec timespec {
    // 设置超时间隔
    .it_interval = {
        .tv_sec = 5,
        .tv_nsec = 0,
    },
    //第一次超时时间
    .it_value = {
        .tv_sec = 5,
        .tv_nsec = 0,
    },
};

//启动定时器
int timeRes = timerfd_settime(fdTimer, 0 /*flags*/, &timespec, nullptr);

// epoll 监听 timerfd
epoll_ctl(mEpollFd, EPOLL_CTL_Add, fdTimer, &eventItem);

while (true)
{   
    // 进入休眠状态
    epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
    if (count < 0)
    {
        perror("epoll failed");
        break;
    }
    for (int i=0;i < count;i++)
    {
        //处理计时器到达事件
    }
}

参考资料

相关推荐
coooliang32 分钟前
【Android】ViewPager的使用
android
xvch3 小时前
Kotlin 2.1.0 入门教程(二十五)类型擦除
android·kotlin
simplepeng11 小时前
我的天,我真是和androidx的字体加载杠上了
android
小猫猫猫◍˃ᵕ˂◍12 小时前
备忘录模式:快速恢复原始数据
android·java·备忘录模式
CYRUS_STUDIO14 小时前
使用 AndroidNativeEmu 调用 JNI 函数
android·逆向·汇编语言
梦否14 小时前
【Android】类加载器&热修复-随记
android
徒步青云15 小时前
Java内存模型
android
今阳15 小时前
鸿蒙开发笔记-6-装饰器之@Require装饰器,@Reusable装饰器
android·app·harmonyos
-优势在我20 小时前
Android TabLayout 实现随意控制item之间的间距
android·java·ui
hedalei20 小时前
android13修改系统Launcher不跟随重力感应旋转
android·launcher