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++)
    {
        //处理计时器到达事件
    }
}

参考资料

相关推荐
kejiashao1 小时前
Android View的绘制流程及事件分发机制
android
小蜜蜂嗡嗡2 小时前
flutter实现付费解锁内容的遮挡
android·flutter
进击的cc2 小时前
拒绝背诵!一文带你打穿 Android ANR 发生的底层全链路
android·面试
进击的cc2 小时前
App 启动优化全家桶:别再只盯着 Application 了,热启动优化你真的做对了吗?
android·面试
彭波3962 小时前
安卓手机端安装xapk、apkm软件!怎样安装xapk软件?安卓的apk和XAPK的区别?附教程
android·智能手机
Yang-Never3 小时前
ADB ->adb shell perfetto 抓取 trace 指令
android·开发语言·adb·android studio
2501_937189236 小时前
莫凡电视:地方台专属聚合 稳定直播播放工具
android·源码·源代码管理
耶叶7 小时前
Android 新权限申请模型(Activity Result API)
android
阿拉斯攀登7 小时前
【RK3576 安卓 JNI/NDK 系列 04】JNI 核心语法(下):字符串、数组与对象操作
android·驱动开发·rk3568·瑞芯微·rk安卓驱动·jni字符串操作
2501_915909067 小时前
不用越狱就看不到 iOS App 内部文件?使用 Keymob 查看和导出应用数据目录
android·ios·小程序·https·uni-app·iphone·webview