当前位置: 代码迷 >> 综合 >> linux 定时器
  详细解决方案

linux 定时器

热度:87   发布时间:2024-02-12 14:58:52.0

第一种  alarm()和signal()

void handler()
{
alarm(10);
}
int main()
{
signal(SIGALRM, handler);//设置与SIGALRM信号触发的函数handler()
handler();
while(1)
{}
return 0;
}

第二种 setitimer

int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue));

  struct itimerval {
struct timeval it_interval;  //定时间隔
struct timeval it_value;   //第一次定时时,的延迟时间
};
struct timeval {
long tv_sec;
long tv_usec;
};

#include <stdio.h>        //printf()
#include <unistd.h>        //pause()
#include <signal.h>        //signal()
#include <string.h>        //memset()
#include <sys/time.h>    //struct itimerval, setitimer()

static int count = 0;

void printMes(int signo)
{
printf("Get a SIGALRM, %d counts!\n", ++count);
}

int main()
{
int res = 0;
struct itimerval tick;

signal(SIGALRM, printMes);//设置与SIGALRM信号触发的函数printMes()
memset(&tick, 0, sizeof(tick));

    //Timeout to run first time
tick.it_value.tv_sec = 1;
tick.it_value.tv_usec = 0;

    //After first, the Interval time for clock
tick.it_interval.tv_sec = 1;
tick.it_interval.tv_usec = 0;

    if(setitimer(ITIMER_REAL, &tick, NULL) < 0)  //设置定时器
printf("Set timer failed!\n");

    //When get a SIGALRM, the main process will enter another loop for pause()
while(1)
{
pause();
}
return 0;
}