用timer设置时钟,并没有产生我预期的计时结果.为什么呢?
我写了个小程序,设置一个2秒钟的计时器,每隔两秒产生一次计时信号,打印出"Caught"语句。主程序sleep 10秒钟,期间一共打印5次计时信号。
代码如下。
创建两个timer。
结果是第一个timer每个2秒响应一次,没有问题
第二个timer每个5秒响应一次,结果第5s钟的时候,进程崩溃了:
Real-time signal 1
#include<signal.h>#include<stdio.h>#include<stdlib.h>#include<time.h>#include<unistd.h>void handler(int sig,siginfo_t*,void*){ if(sig==SIGRTMIN){printf("Caught %d\n",sig);} else if(sig==SIGRTMIN+1){ }}timer_t createTimer(int sig, double secs){ sigevent sev; timer_t timerid; sev.sigev_notify=SIGEV_SIGNAL; sev.sigev_signo =sig; sev.sigev_value.sival_ptr=&timerid; if(timer_create(CLOCK_REALTIME,&sev,&timerid)==-1)return 0; long freq_nanosecs=(long)secs*1000000000; itimerspec its; its.it_value.tv_sec =freq_nanosecs/1000000000; its.it_value.tv_nsec =freq_nanosecs%1000000000; its.it_interval.tv_sec =its.it_value.tv_sec; its.it_interval.tv_nsec=its.it_value.tv_nsec; if(timer_settime(timerid,0,&its,NULL)==-1)return 0; return timerid;}int main(void){ struct sigaction sa; sa.sa_flags=SA_SIGINFO; sa.sa_sigaction=handler; sigemptyset(&sa.sa_mask); if(sigaction(SIGRTMIN,&sa,NULL)==-1)return 1; createTimer(SIGRTMIN,2); createTimer(SIGRTMIN+1,5); int left=10; do{left=sleep(left);}while(left>0); return 0;}