这是我自己实现的版本,参考 Don Libes 的 Implementing Software Timer
我是用alarm实现的,好像不太精确,还有一个版本可以设定定时器的次数,可是随着次数增多精确度就成了不可忽略的问题了。
不排除有很多BUG, 而且有些细节没考虑。
/************** timers.h *************/ /* * Title: Answer to excersice 10.5 of APUE - Software timer * By: Leon * * This implementation is similar to Don Libes's, and I modify * it according to my thought. This timer is not very precise. */ #ifndef _APUE_TIMER_ #define _APUE_TIMER_ #include <stdio.h> #include <limits.h> #include <signal.h> #include <sys/times.h> #include <time.h> #include <assert.h> #include <unistd.h> #define TRUE 1 #define FALSE 0 #define MAX_TIMERS 128 /* number of timers */ #define VERY_LONG_TIME INT_MAX /* longest time possible */ /* * no return value, the function takes * only one parameter for general purpose. */ typedef void timer_handler(void *arg); struct __apue_timer { int inuse; /* TRUE if in use */ int time_wait; /* relative time to wait */ timer_handler *handler; /* called when the timer has expired */ void *arg; /* argument of handler */ }; typedef struct __apue_timer ATIMER; /* * initialize the timers array. * This function must be called first. * returns 0 on success and -1 on error. */ int timer_init(void); /* * stop and cancel all timers. * after this function was called, don't use