linux应用程序中的延时和定时器

笔记:

在linux应用程序中延时有sleep()、msleep()和usleep()函数之类的延时,也有如下形式的延时:

    struct timeval delay;
    delay.tv_sec = sleepSecond;
    delay.tv_usec = 0;
    select( 0, NULL, NULL, NULL, &delay );

但是基本上都是基于进程休眠的,好像没有循环等待的延时,有待证实,目前没发现。


考虑到一个问题,如果定时发送信号,执行相应一个信号处理函数时,该函数还么有执行完成,另一个信号又来了,怎么处理呢?答案是等待前面一个信号处理完成。

定时器配合kill函数一起使用,可以满足某些想立即执行又要有周期执行相应函数的特殊要求,如下:

/*********************************************************************************
 *      Copyright:  (C) 2014 EAST
 *                  All rights reserved.
 *
 *       Filename:  setitimer.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(08/08/2014)
 *         Author:  fulinux 
 *      ChangeLog:  1, Release initial version on "08/08/2014 12:58:48 PM"
 *                 
 ********************************************************************************/
#include 
#include 
#include 
#include 
#include 
#include 

static int switch_val = 0;

void sigroutine(int signo){
    switch (signo){
        case SIGALRM:
            printf("Catch a signal -- SIGALRM \n");
            break;
        case SIGVTALRM:
            printf("Catch a signal -- SIGVTALRM \n");
            switch(switch_val){
                case 0:
                    printf ("switch_val =  0\n");
                    break;
                case 1:
                    printf ("switch_val =  1\n");
                    break;
                case 2:
                    printf ("switch_val =  2\n");
                    break;
                case 3:
                    printf ("switch_val =  3\n");
                    break;
                default:
                    return;
            }
            break;
    }
    return;
}
int main()
{
    struct itimerval value, ovalue, value2;          //(1)

    printf("process id is %d\n", getpid());

    signal(SIGALRM, sigroutine);
    signal(SIGVTALRM, sigroutine);

    value.it_value.tv_sec = 1;
    value.it_value.tv_usec = 0;
    value.it_interval.tv_sec = 1;
    value.it_interval.tv_usec = 0;
    setitimer(ITIMER_REAL, &value, &ovalue);     //(2)
    value2.it_value.tv_sec = 0;
    value2.it_value.tv_usec = 1;
    value2.it_interval.tv_sec = 0;
    value2.it_interval.tv_usec = 500000;
    setitimer(ITIMER_VIRTUAL, &value2, &ovalue);

#if 0
    struct timeval delay;
    delay.tv_sec = 0;
    delay.tv_usec = 500000;
    select(0, NULL, NULL, NULL, &delay);
#endif
    switch_val = 1;
    kill(getpid(), SIGVTALRM);
    printf ("fulinux 1\n");

    switch_val = 2;
    kill(getpid(), SIGVTALRM);
    printf ("fulinux 2\n");

    switch_val = 3;
    kill(getpid(), SIGVTALRM);
    printf ("fulinux 3\n");

    for(;;)
        ;
}


你可能感兴趣的:(信号处理篇,linux函数篇,linux技巧篇)