How to make a C timer expire at a particular system time in Linux

微笑、不失礼 提交于 2019-12-06 00:14:17

That same rule is found in the manpage for timer_settime, with some additional explanation:

By default, the initial expiration time specified in new_value->it_value is interpreted relative to the current time on the timer's clock at the time of the call. This can be modified by specifying TIMER_ABSTIME in flags, in which case new_value->it_value is interpreted as an absolute value as measured on the timer's clock; that is, the timer will expire when the clock value reaches the value specified by new_value->it_value. If the specified absolute time has already passed, then the timer expires immediately, and the overrun count (see timer_getoverrun(2)) will be set correctly.

If the value of the CLOCK_REALTIME clock is adjusted while an absolute timer based on that clock is armed, then the expiration of the timer will be appropriately adjusted. Adjustments to the CLOCK_REALTIME clock have no effect on relative timers based on that clock.

Yes, you've been setting a relative timer, and that's why it ignores the adjustment to the system time.

You might try the following:

struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);

struct itimerspec its;
its.it_value.tv_sec     = ts.tv_sec + 1;
its.it_value.tv_nsec    = ts.tv_nsec;
its.it_interval.tv_sec  = 60;
its.it_interval.tv_nsec = 0;
timer_settime(timerID, TIMER_ABSTIME, &its, NULL);

Try this:

struct timeval tv;
gettimeofday(&tv, NULL);

struct itimerspec its;
its.it_value.tv_sec     = 1;
its.it_value.tv_nsec    = 0;
its.it_interval.tv_sec  = tv_sec + 60;
its.it_interval.tv_nsec = tv_nsec;
timer_settime(timerID, TIMER_ABSTIME, &its, NULL);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!