timerfd是Linux为用户程序提供的一个定时器接口。这个接口基于文件描述符,通过文件描述符的可读事件进行超时通知,所以能够被用于select/poll的应用场景。
int timerfd_create(intclockid, intflags);
int timerfd_settime(intfd, intflags, const struct itimerspec *new_value, struct itimerspec *old_value);
int timerfd_gettime(intfd, struct itimerspec *curr_value);
===================================================
1.函数 timerfd_create
int timerfd_create(intclockid, intflags);
它是用来创建一个定时器描述符 timerfd
第一个参数:clockid指定时间类型,有两个值:
CLOCK_REALTIME :Systemwide realtime clock. 系统范围内的实时时钟
CLOCK_MONOTONIC:以固定的速率运行,从不进行调整和复位 ,它不受任何系统time-of-day时钟修改的影响
第二个参数:flags可以是0或者O_CLOEXEC/O_NONBLOCK。
返回值:timerfd(文件描述符)
-------------------------------------------------------------------------------
文件描述符 timerfd 要设置的超时结构体
struct timespec {
time_t tv_sec; /*Seconds*/
long tv_nsec; /*Nanoseconds*/
};
结构体itimerspec就是timerfd要设置的超时结构体
struct itimerspec {
struct timespec it_interval; /*Interval for periodic timer*/
struct timespec it_value; /*Initial expiration*/
};
it_value表示定时器第一次超时时间,
it_interval表示之后的超时时间即每隔多长时间超时
===========================================
2.函数 timerfd_settime
int timerfd_settime(
intfd,
intflags,
const struct itimerspec *new_value,
struct itimerspec *old_value);
函数作用:用来启动或关闭有fd指定的定时器
参数说明:
fd:文件描述符timerfd, timerfd_create函数返回
fnew_value:
/***********************************
指定新的超时时间,
设定new_value.it_value非零则启动定时器,否则关闭定时器,
如果new_value.it_interval为0,则定时器只定时一次,即最开始的那次;
不为0,则为超时时间间隔,之后每隔设定时间超时一次
***********************************/
old_value:不为null,则返回定时器这次设置之前的超时时间
flags: 1代表设置的是绝对时间;为0代表相对时间
========================================
3.函数 timerfd_gettime
int timerfd_gettime(intfd, struct itimerspec *curr_value);
此函数返回文件描述符fd所标识定时器的间隔及剩余时间。间隔以及距离下次到期的时间均返回curr_value指向的结构itimerspec中,用于获得定时器距离下次超时还剩下的时间。
如果调用时定时器已经到期,并且该定时器处于循环模式(设置超时时间时struct itimerspec::it_interval不为0),那么调用此函数之后定时器重新开始计时。
=======================================
4.函数timerfd_release
函数释放timerfd_create函数中申请的资源,删除已分配的定时器。