linux下定时器实现函数setitimer和alarm限于signal类型,最多只支持3个不同时间的定时器,虽说是3个,但相互之间有影响,同时和sleep冲突。网上看有用select+线程进行定时器模拟,以下是自己适用的代码,欢迎大家指正。
#ifndef _MUL_TIMER_H_
#define _MUL_TIMER_H_
#define _TIMER_TEST_
#ifdef _TIMER_TEST_
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#define IN
#define OUT
#else
#include "includes.h"
#endif
typedef void* TIMER_FD;
typedef void* PVOID;
typedef unsigned char BOOL_T;
#define TRUE 1
#define FALSE 0
typedef void (*PTIME_CALLBACK)(PVOID pdata);
typedef struct _timer_handle{
unsigned char stop;
unsigned char repeat;
unsigned int timeout;
pthread_t timer_thread;
PTIME_CALLBACK pfunc;
PVOID pdata;
}timer_handle,*ptimer_handle;
int init_timer(IN TIMER_FD* pTimer_fd,
IN PTIME_CALLBACK pTimerFunc,
IN PVOID pData,
IN BOOL_T Repeat);
void set_timer(TIMER_FD Timer_fd, int ntimeoutms);
void kill_timer(TIMER_FD Timer_fd);
void modify_timer(TIMER_FD Timer_fd);
#endif
#include "mul_timer.h"
void* timer_proc(void* pdata)
{
struct timeval tv = {0};
timer_handle* phandle = (timer_handle*)pdata;
while(phandle->repeat && !(phandle->stop)){
tv.tv_sec=phandle->timeout/1000;
tv.tv_usec=(phandle->timeout%1000)*1000;
int nret = select(0,NULL,NULL,NULL,&tv);
if(0 == nret){
phandle->pfunc(phandle->pdata);
}
}
return NULL;
}
int init_timer(IN TIMER_FD* pTimer_fd,
IN PTIME_CALLBACK pTimerFunc,
IN PVOID pData,
IN BOOL_T Repeat)
{
ptimer_handle phandle = (ptimer_handle)malloc(sizeof(timer_handle));
if(NULL == phandle)
return 0;
phandle->repeat = Repeat;
phandle->pfunc = pTimerFunc;
phandle->pdata = pData;
*pTimer_fd = (void*)phandle;
return 1;
}
void set_timer(TIMER_FD Timer_fd, int ntimeoutms)
{
timer_handle* phandle = (timer_handle*)Timer_fd;
phandle->timeout = ntimeoutms;
phandle->stop = FALSE;
pthread_create(&(phandle->timer_thread), NULL, timer_proc, phandle);
}
void kill_timer(TIMER_FD Timer_fd)
{
void* thread_result;
timer_handle* phandle = (timer_handle*)Timer_fd;
phandle->stop = TRUE;
pthread_join(phandle->timer_thread, &thread_result);
free(phandle);
phandle = NULL;
}
void modify_timer(TIMER_FD Timer_fd)
{
}
#ifdef _TIMER_TEST_
void print_test(PVOID pdata)
{
struct tm *local;
time_t t;
t = time(0);
local = localtime(&t);
printf("[%d:%d:%d] ",local->tm_hour,
local->tm_min,
local->tm_sec);
char* phandle = (char*)pdata;
printf("timer ID = %s", phandle);
}
int main(void)
{
TIMER_FD tfd1;
char* pname1 = "timer1";
init_timer(&tfd1, print_test, (void*)pname1, TRUE);
set_timer(tfd1, 1000);
TIMER_FD tfd2;
char* pname2 = "timer2";
init_timer(&tfd1, print_test, (void*)pname2, TRUE);
set_timer(tfd1, 1000);
TIMER_FD tfd3;
char* pname3 = "timer3";
init_timer(&tfd1, print_test, (void*)pname3, TRUE);
set_timer(tfd1, 500);
for(;;)
;
}
#endif