LINUX定时器--使用
程序员文章站
2022-05-08 10:00:25
...
封装一下定时器。
timer.h
#ifndef TIMER_H
#define TIMER_H
#define TIMER_INVALID_TIMER_ID (~0UL)
#ifndef ULONG
#define ULONG unsigned long
#endif
#ifndef VOID
#define VOID void
#endif
typedef VOID(*TIMER_FUNC_PF)(VOID*);
typedef enum
{
TIMER_LOOP = 0,
TIMER_NO_LOOP,
}TIMER_MODE_E;
extern ULONG TimerCreate(TIMER_MODE_E enMode,
TIMER_FUNC_PF func,
VOID *pPara,
ULONG ulmSecond);
extern VOID TimerDestory(ULONG ulTimerId);
#endif
timer.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include "timer.h"
ULONG TimerCreate(TIMER_MODE_E enMode, TIMER_FUNC_PF func, VOID *pPara, ULONG ulmSecond)
{
ULONG ulTimerId = TIMER_INVALID_TIMER_ID;
int iRet = 0;
struct sigevent ev;
struct itimerspec tev;
if (NULL == func || NULL == pPara)
{
return ulTimerId;
}
memset(&ev, 0, sizeof(struct sigevent));
ev.sigev_notify = SIGEV_THREAD;
ev.sigev_signo = SIGALRM;
ev.sigev_value.sival_ptr = pPara;
ev.sigev_notify_function = (void(*)(sigval_t))func;
iRet = timer_create(CLOCK_REALTIME, &ev, (timer_t*)&ulTimerId);
if (0 == iRet)
{
memset(&tev, 0, sizeof(struct itimerspec));
tev.it_value.tv_sec = ulmSecond / 1000;
tev.it_value.tv_nsec = (ulmSecond % 1000) * 1000 * 1000;
if (TIMER_LOOP == enMode)
{
tev.it_interval = tev.it_value;
}
iRet = timer_settime((timer_t)ulTimerId, TIMER_ABSTIME, &tev, NULL);
if (0 != iRet)
{
TimerDestory(ulTimerId);
ulTimerId = TIMER_INVALID_TIMER_ID;
}
}
return ulTimerId;
}
VOID TimerDestory(ULONG ulTimerId)
{
if (TIMER_INVALID_TIMER_ID != ulTimerId)
{
timer_delete((timer_t)ulTimerId);
}
return;
}
测试(进度条):
main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include "timer.h"
void probar( VOID * pRate)
{
char buf[101];
int rate = (*(int*)pRate)%101;
const char *sta="-\\|/";
memset(buf, '=',sizeof(buf));
buf[100] = '\0';
printf("[%-100s],%3d%%,[%c]\r",buf + 100 - rate,rate,sta[rate%4]);
fflush(stdout);
(*(int*)pRate) = rate + 1;
return;
}
int main ()
{
int num= 0;
ULONG ulTimerId = TIMER_INVALID_TIMER_ID;
ulTimerId = TimerCreate(TIMER_LOOP,probar,(VOID*)&num,100);
getchar();
TimerDestory(ulTimerId);
return 0;
}
编译:要指定 -lrt
上一篇: java定时器Timer对象
下一篇: 杂乱无章的记录