创建、初始化以及删除一个定时器分别对应如下三个函数:timer_create、timer_settime、timer_delete
#include<time.h>
inttimer_create(clockid_t clock_id, struct sigevent *evp,timer_t*timerid)
创建的定时器是每个进程自己的,不是在fork时继承的。
参数:
clock_id说明定时器是基于哪个时钟的。可以为:
CLOCK_REALTIME:Systemwide realtime clock.
CLOCK_MONOTONIC:Representsmonotonic time. Cannot be set.
CLOCK_PROCESS_CPUTIME_ID:High resolution per-process timer.
CLOCK_THREAD_CPUTIME_ID:Thread-specific timer.
CLOCK_REALTIME_HR:High resolution version of CLOCK_REALTIME.
CLOCK_MONOTONIC_HR:High resolution version of CLOCK_MONOTONIC.
evp指定了定时器到期要产生的异步通知。如果evp为NULL,那么定时器到期会产生默认的信号,对CLOCK_REALTIMER来说,默认信号就是SIGALRM。
*timerid装载的是被创建的定时器的ID。
sigevent - structure for notification from asynchronous routines
unionsigval { /*Data passed with notification */
int sival_int; /* Integervalue */
void *sival_ptr; /* Pointer value */
};
struct sigevent {
int sigev_notify; /* Notification method */
int sigev_signo; /* Notification signal */
unionsigval sigev_value; /* Data passed with notification */
void (*sigev_notify_function) (union sigval);
/* Function used for thread notification (SIGEV_THREAD) */
void *sigev_notify_attributes;
/* Attributes for notification thread (SIGEV_THREAD) */
pid_t sigev_notify_thread_id;
/* ID of thread to signal (SIGEV_THREAD_ID) */
};
其中evp->sigev_notify可为
SIGEV_NONE:什么都不做,只提供通过timer_gettime和timer_getoverrun查询超时信息
SIGEV_SIGNAL:当定时器到期,内核会将sigev_signo所指定的信号传送给进程。在信号处理程序中,si_value会被设定会sigev_value。
SIGEV_THREAD:当定时器到期,内核会(在此进程内)以sigev_notification_attributes为线程属性创建一个线程,并且让它执行sigev_notify_function,传入sigev_value作为为一个参数。
inttimer_settime(timer_t timerid, int flags, const struct itimerspec*value, struct itimerspect *ovalue);
struct timespec {
time_t tv_sec; /* Seconds */
long tv_nsec; /* Nanoseconds */
};
struct itimerspec {
struct timespec it_interval; /* Timer interval */
struct timespec it_value; /* Initial expiration */
};
it_value用于指定当前的定时器到期时间。当定时器到期,it_value的值会被更新成it_interval的值。
inttimer_delete (timer_t timerid);
一次成功的timer_delete()调用会销毁关联到timerid的定时器并且返回0。执行失败时,此调用会返回-1并将errno设定会EINVAL,这个唯一的错误情况代表timerid不是一个有效的定时器。