Linux新增API:timerfd

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值