1. 程式人生 > >linux應用程式中的延時和定時器

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 <
[email protected]
> * ChangeLog: 1, Release initial version on "08/08/2014 12:58:48 PM" * ********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <time.h> #include <sys/time.h> 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(;;) ; }