linux 定时器

第一种  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        //printf()
#include        //pause()
#include        //signal()
#include        //memset()
#include    //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;
}

你可能感兴趣的:(linux,定时)