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

参考资料

相关推荐
原神启动116 分钟前
Ansible(三)—— 使用Ansible自动化部署LNMP环境
android·自动化·ansible
前端老白30 分钟前
webview在微信小程序中,安卓加载失败,IOS正常加载
android·ios·微信小程序·webview
2501_9371549330 分钟前
适配中兴主流机型 纯净版刷机固件技术优势合集
android·源码·源代码管理·机顶盒
2501_9151063231 分钟前
用 HBuilder 上架 iOS 应用时如何管理Bundle ID、证书与描述文件
android·ios·小程序·https·uni-app·iphone·webview
TheNextByte140 分钟前
如何通过OTG或不使用OTG将文件从Android传到U盘
android
2501_9159090641 分钟前
资源文件混淆在 iOS 应用安全中的实际价值
android·安全·ios·小程序·uni-app·iphone·webview
2501_9159184141 分钟前
iOS App 性能测试中常被忽略的运行期问题
android·ios·小程序·https·uni-app·iphone·webview
天勤量化大唯粉1 小时前
基于距离的配对交易策略:捕捉价差异常偏离的均值回归机会(天勤量化代码实现)
android·开发语言·python·算法·kotlin·开源软件·策略模式
走在路上的菜鸟1 小时前
Android学Dart学习笔记第二十二节 类-扩展方法
android·笔记·学习·flutter
csj501 小时前
安卓基础之《(7)—中级控件(1)图形定制》
android