点击(此处)折叠或打开
-
#include
-
int timerfd_create(int clockid, int flags);
-
int timerfd_settime(int fd, int flags, const struct itimerspec *new_value,struct itimerspec *old_value);
-
int timerfd_gettime(int fd, struct itimerspec *curr_value);
timerfd_create:创建一个timerfd;返回的fd可以进行如下操作:read、select(poll、epoll)、close
timerfd_settime:设置timer的周期,以及起始间隔
timerfd_gettime:获取到期时间。
点击(此处)折叠或打开
-
//函数参数中数据结构如下:
-
struct timespec
-
{
-
time_t tv_sec; /* Seconds */
-
long tv_nsec; /* Nanoseconds */
-
};
-
struct itimerspec
-
{
-
struct timespec it_interval; /* Interval for periodic timer */
-
struct timespec it_value; /* Initial expiration */
-
};
l例子
点击(此处)折叠或打开
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include /* Definition of uint64_t */
-
-
#define handle_error(msg)
-
do { perror(msg); exit(EXIT_FAILURE); } while (0)
-
-
void printTime()
-
{
-
struct timeval tv;
-
gettimeofday(&tv, NULL);
-
printf("printTime: current time:%ld.%ld ", tv.tv_sec, tv.tv_usec);
-
}
-
-
int main(int argc, char *argv[])
-
{
-
struct timespec now;
-
if (clock_gettime(CLOCK_REALTIME, &now) == -1)
-
handle_error("clock_gettime");
-
-
struct itimerspec new_value;
-
new_value.it_value.tv_sec = now.tv_sec + atoi(argv[1]);
-
new_value.it_value.tv_nsec = now.tv_nsec;
-
new_value.it_interval.tv_sec = atoi(argv[2]);
-
new_value.it_interval.tv_nsec = 0;
-
-
int fd = timerfd_create(CLOCK_REALTIME, 0);
-
if (fd == -1)
-
handle_error("timerfd_create");
-
-
if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == -1)
-
handle_error("timerfd_settime");
-
-
printTime();
-
printf("timer startedn");
-
-
for (uint64_t tot_exp = 0; tot_exp < atoi(argv[3]);)
-
{
-
uint64_t exp;
-
ssize_t s = read(fd, &exp, sizeof(uint64_t));
-
if (s != sizeof(uint64_t))
-
handle_error("read");
-
-
tot_exp += exp;
-
printTime();
-
printf("read: %llu; total=%llun",exp, tot_exp);
-
}
-
-
exit(EXIT_SUCCESS);
-
}
代码L25-L29:初始化定时器的参数,初始间隔与定时间隔。
L32:创建定时器fd,CLOCK_REALTIME:真实时间类型,修改时钟会影响定时器;CLOCK_MONOTONIC:相对时间类型,修改时钟不影响定时器。
L35:设置定时器的值。
L44:阻塞等待定时器到期。返回值是未处理的到期次数。比如定时间隔为2秒,但过了10秒才去读取,则读取的值是5。
编译运行:编译时要加rt库(g++ -lrt timerfd.cc -o timerfd)
(编辑:应用网_丽江站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|