POSIX定时器timer_create、timer_settime、timer_delete

创建、初始化以及删除一个定时器分别对应如下三个函数:timer_createtimer_settimetimer_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指定了定时器到期要产生的异步通知。如果evpNULL,那么定时器到期会产生默认的信号,对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_gettimetimer_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不是一个有效的定时器。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值