setitimer函數

setitimer函數爲設置定時器(鬧鐘),可替代alarm函數,比alarm函數精確度更高,精度爲微秒,可以實現週期定時。

函數頭文件爲 #include<sys/time.h>
函數原型爲 int setitimer(int which,const struct itimerval *new_value,struct itimerval *old_value);

參數which 指定定時方式:
ITIMER_REAL 計時實際時間,到達時間,產生SIGALRM信號
ITIMER_VIRTUAL 該計時器根據進程消耗的用戶模式CPU時間進行倒計時。 (該度量包括進程中所有線程消耗的CPU時間。)在每次到期時,都會生成SIGVTALRM信號。
ITIMER_PROF 根據進程消耗的總CPU時間(即用戶和系統)進行倒計時.

new_value爲傳入參數 表示定時的時長

old_value爲傳出參數 表示上一次定時剩餘的時間,例如第一次定時10s,但是過了3s後,再次用setitimer函數定時,此時第二次的計時會將第一次計時覆蓋,而上一次定時的剩餘時間則爲7s。

new_value和old_value的數據結構爲:

struct itimerval {
   struct timeval it_interval; /* Interval for periodic timer */
   struct timeval it_value;    /* Time until next expiration */
};

struct timeval {
   time_t      tv_sec;         /* seconds */
   suseconds_t tv_usec;        /* microseconds */
};

it_value爲計時時長,it_interval爲定時器的間隔,即第一次計時it_value時長髮送信號,再往後的信號每隔一個it_interval發送一次。

下面代碼通過封裝一個my_alarm函數來練習setitimer函數的使用,改代碼功能爲求機器在一秒內能數多少次數。

  1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<stdlib.h>
  4 #include<sys/time.h>
  5 #include<sys/types.h>
  6 #include<sys/stat.h>
  7 unsigned int my_alarm(unsigned int sec)
  8 {
  9     struct itimerval it,oldit;
 10     it.it_value.tv_sec = sec;
 11     it.it_value.tv_usec = 0;
 12     it.it_interval.tv_sec = 0;
 13     it.it_interval.tv_usec = 0;
 14 
 15     int num = setitimer(ITIMER_REAL,&it,&oldit);
 16     if(num == -1)
 17     {
 18         perror("setitimer");
 19         exit(1);
 20     }
 21     return oldit.it_value.tv_sec;
 22 }
 23 int main(void)
 24 {
 25     int i;
 26     //alarm(1);
 27 
 28     my_alarm(1);
 29     for(i = 0; ;i++)
 30     {
 31         printf("%d\n",i);
 32     }
 33     return 0;
 34 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章