Timer
1.setitimer.c
#include <stdio.h> #include <signal.h> #include <sys/time.h> #include <errno.h> #include <stdlib.h> struct itimerval timer; void Time_Fun(int temp) { printf("Time_Fun text ok! "); } int main(void) { signal(SIGALRM, Time_Fun); //信号处理函数 timer.it_value.tv_sec =0; //设置定时器后间隔多久开始执行定时任务 timer.it_value.tv_usec =1; timer.it_interval.tv_sec =1; //两次定时任务之间的时间间隔 timer.it_interval.tv_usec =0; if( setitimer(ITIMER_REAL,&timer,NULL)<0 ){ perror("setitimer failed ! "); exit(0); } for(;;){} return 0; }
2.alarm.c
#include <stdio.h> #include <unistd.h> #include <signal.h> void Time_Fun(int temp) { printf("Time_Fun text ok! "); alarm(1); //覆盖前一个 } int main(void) { signal(SIGALRM, Time_Fun); //信号处理函数 alarm(1); for(;;){} return 0; }
3.sleep.c
#include <stdio.h> #include <unistd.h> #include <signal.h> #include <string.h> void Time_Fun(int temp) { printf("Time_Fun text ok! "); } int main(void) { signal(SIGALRM, Time_Fun); //信号处理函数 for(;;){ kill(getpid(),SIGALRM); //信号发送函数 sleep(1); } return 0; }