Linux中, 系統為每個系統都維護了三種計時器,分別為: 真實計數器, 虛擬計時器以及實用計時器, 一般情況下都使用真實計時器 getitimer()/setitimer() which //具體的計時器類型 1. ITIMER_REAL :真實計時器 統計進程消耗的真實時間 通過定時產生SIGA ...
Linux中, 系統為每個系統都維護了三種計時器,分別為: 真實計數器, 虛擬計時器以及實用計時器, 一般情況下都使用真實計時器
getitimer()/setitimer()
//讀取/設置內部計時器
#include <sys/time.h>
int getitimer(int which, struct itimerval *curr_value);
int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value);
which //具體的計時器類型
- ITIMER_REAL :真實計時器
- 統計進程消耗的真實時間
- 通過定時產生SIGALRM工作
- ITIMER_VIRTUAL :虛擬計時器
- 統計繼承在用戶態下消耗的時間
- 通過定時產生SIGVTALRM工作
- ITIMER_PROF :實用計時器
- 統計進程在用戶態和內核態消耗的總時間
- 通過定時產生SIGPROF工作
new_value://結構體指針, 用於設計計時器的新值
old_value://結構體指針, 用於獲取計時器的舊值
struct itimerval {
struct timeval it_interval; /* next value */
struct timeval it_value; /* current value */
};
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds *///10^6
}
//timer
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/time.h>
#include<signal.h>
#include<sys/types.h>
void fa(int signo){
printf("random\n");
}
int main(){
//設置對信號SIGALRM進行自定義處理
if(SIG_ERR==signal(SIGALRM,fa))
perror("signal"),exit(-1);
struct itimerval timer;
//設置間隔時間
timer.it_interval.tv_sec=2;
timer.it_interval.tv_usec=300000;
//設置啟動時間
timer.it_value.tv_sec=5;
timer.it_value.tv_usec=0;
int res=setitimer(ITIMER_REAL,&timer,NULL);
if(-1==res)
perror("setitimer"),exit(-1);
getchar();
itimer.it_value.tv_sec=0;
setitimer(ITIMER_REAL,&timer,NULL); //沒有錯誤處理
while(1);
return 0;
}