#include<stdio.h>#include<signal.h>#include<unistd.h>voidhandle_alarm(int sig)//sig is 14(SIGALRM){psignal(sig,NULL);//will print: Alarm clockprintf("raise an alarm per 3s: %d\n", sig);alarm(3);}intmain(void){signal(SIGALRM, handle_alarm);alarm(3);while(1){sleep(1);}return0;}
setitimer
头文件<sys/time.h>
根据设置的首次触发时间和时间间隔触发SIGALRM信号
#include<stdio.h>#include<sys/time.h>#include<signal.h>voidhandle(int sig){printf("raise an alarm: %d\n", sig);//will print 14}intmain(){signal(SIGALRM, handle);//will raise an alarm signal after 3s and ther per 1sstructitimerspec value ={1,0,3,0};setitimer(CLOCK_REALTIME,&value,NULL);while(1);}
POSIX定时器
头文件<time.h>,需要链接库rt
函数:timer_create、timer_settime、timer_delete
定时触发信号
#include<stdio.h>#include<time.h>#include<signal.h>voidhandle_alarm(int sig){printf("raise an alarm signal %d\n", sig);}intmain(){signal(SIGALRM, handle_alarm);//设置信号处理函数timer_t timer;structsigevent evp ={0};//初始化全0
evp.sigev_notify = SIGEV_SIGNAL;//通知类型为通过信号
evp.sigev_signo = SIGALRM;timer_create(CLOCK_REALTIME,&evp,&timer);structitimerspec value ={1,0,3,0};//3s触发1次,然后每隔1s触发1次timer_settime(timer,0,&value,NULL);//flags为0表示value是相对时间while(1);}
定时创建新线程执行自定义函数
#include<stdio.h>#include<time.h>#include<signal.h>#include<string.h>#include<pthread.h>voidhandle(sigval_t val){printf("timer raise to create a new thread[%lu]: %d\n",pthread_self(), val.sival_int);//will print new thread_id and 66}intmain(){printf("main thread[%lu]\n",pthread_self());timer_t timer;//定时器idstructsigevent evp ={0};//初始化全0
evp.sigev_notify = SIGEV_THREAD;
evp.sigev_notify_function= handle;//线程执行函数
evp.sigev_value.sival_int =66;//处理函数的参数timer_create(CLOCK_REALTIME,&evp,&timer);structitimerspec value ={1,0,3,0};//3s触发1次,然后每隔1s触发1次timer_settime(timer,0,&value,NULL);//flags为0表示value是相对时间while(1);}