定时器

1、信号量 SIGALRM + alarm()

函数说明:alarm()用来设置信号SIGALRM 在经过参数seconds 指定的秒数后传送给目前的进程. 如果参数seconds 为0, 则之前设置的闹钟会被取消, 并将剩下的时间返回.
返回值:返回之前闹钟的剩余秒数, 如果之前未设闹钟则返回0.

#include <unistd.h>
#include <signal.h>
void handler()
{
    printf("hello
");
}

main()
{
    int i;
    signal(SIGALRM, handler);
    alarm(5);
    for(i = 1; i < 7; i++)
    {
        printf("sleep %d ...
", i);
        sleep(1);
    }
}

2、setitimer  转( http://www.cnblogs.com/dandingyy/articles/2653218.html )

Not Standard Library,setitimer()有两个功能,一是指定一段时间后,才执行某个function,二是每间格一段时间就执行某个function。

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;
  };

其中,which为定时器类型,3中类型定时器如下:

  ITIMER_REAL : 以系统真实的时间来计算,它送出SIGALRM信号。  

  ITIMER_VIRTUAL : -以该进程在用户态下花费的时间来计算,它送出SIGVTALRM信号。  

  ITIMER_PROF : 以该进程在用户态下和内核态下所费的时间来计算,它送出SIGPROF信号。

#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!
", ++count);
}

int main()
{
    int res = 0;
    struct itimerval tick;
    
    signal(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!
");

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

3、使用select()

#include <sys/time.h>
#include <sys/select.h>
#include <time.h>
#include <stdio.h>

/*seconds: the seconds; mseconds: the micro seconds*/
void setTimer(int seconds, int mseconds)
{
        struct timeval temp;

        temp.tv_sec = seconds;
        temp.tv_usec = mseconds;

        select(0, NULL, NULL, NULL, &temp);
        printf("timer
");

        return ;
}

int main()
{
        int i;

        for(i = 0 ; i < 100; i++)
                setTimer(1, 0);

        return 0;
}
原文地址:https://www.cnblogs.com/csun/p/6246800.html