Linux新增API:timerfd
timerfd
- 函数功能:通过文件I/O方式去获取定时器的通知事件
- 相关API:
- 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);
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 */
};
it_value是首次超时时间,需要填写从clock_gettime获取的时间,并加上要超时的时间。 it_interval是后续周期性超时时间,是多少时间就填写多少。
void print_time()
{
struct timeval tv;
gettimeofday(&tv, NULL);
printf("current time: %ld.%ld\n", tv.tv_sec, tv.tv_usec);
}
int main(int argc, char *argv[])
{
/* Pre use timerfd_settime Need to call clock_gettime gets the current time */
struct timespec now;
if ((clock_gettime(CLOCK_REALTIME, &now)) == -1)
handle_error("clock_gettime");
/* Set timeout */
struct itimerspec new_value;
/* 10 seconds later, first timeout */
new_value.it_value.tv_sec = now.tv_sec + 5;
new_value.it_value.tv_nsec= now.tv_nsec;
/* The signal occurs every 3 seconds */
new_value.it_interval.tv_sec = 1;
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");
print_time();
printf("time started\n");
for(uint64_t tot_exp = 0; tot_exp < 10;) //timer run times: 20
{
uint64_t exp;
ssize_t s = read(fd, &exp, sizeof(uint64_t));
if (s != sizeof(uint64_t))
handle_error("read");
tot_exp += exp;
print_time();
printf("read: %llu, total: %llu", exp, tot_exp);
}
return 0;
}
执行结果
current time: 1648031374.293403
time started
current time: 1648031379.294579
read: 1, total: 1current time: 1648031380.294439
read: 1, total: 2current time: 1648031381.294464
read: 1, total: 3current time: 1648031382.294013
read: 1, total: 4current time: 1648031383.294167
read: 1, total: 5current time: 1648031384.293585
read: 1, total: 6current time: 1648031385.294088
read: 1, total: 7current time: 1648031386.294429
read: 1, total: 8current time: 1648031387.293897
read: 1, total: 9current time: 1648031388.294057