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

参考资料

相关推荐
xzkyd outpaper1 小时前
Kotlin中Flow
android·开发语言·kotlin
byte轻骑兵2 小时前
【Bluedroid】bta_av_sink_media_callback(BTA_AV_SINK_MEDIA_CFG_EVT)流程源码分析
android·c++·bluedroid
鹏多多.3 小时前
flutter-完美解决键盘弹出遮挡输入框的问题
android·flutter·ios·前端框架
干一行,爱一行4 小时前
如何在android framewrok dump camera data
android·camera
我命由我123454 小时前
Android Studio 提示信息 ‘equals(““)‘ can be replaced with ‘isEmpty()‘
android·ide·android studio·安卓·android jetpack·android-studio·android runtime
Bryce李小白5 小时前
Flutter实现Android原生相机拍照
android·数码相机·flutter
初学者-Study5 小时前
Android基础(一) 运行HelloWorld
android·helloworld·模拟器运行
BUG创建者5 小时前
openlayer根据不同的状态显示不同的图层颜色
android·java·javascript
用户2018792831676 小时前
浅谈画框ImageView的background和src属性的差异
android
2501_915909066 小时前
iOS 加固工具实战解析,主流平台审核机制与工具应对策略
android·ios·小程序·https·uni-app·iphone·webview