- alarm
- setitimer
● alarm
#include <unistd.h>這是一個簡單的設定Timer介面。當呼叫了alarm( n )後,等待n秒後,就會觸發一次的SIGALRM的signal,所以必須要在呼叫alarm前,先設好SIGALRM的handler function才行。而當乎呼alarm(0)時,則表示停止當前的timer處理,不要發出SIGALRM的signal。
unsigned int alarm(unsigned int seconds);
Return value : 返回上一次呼叫alarm的剩餘秒數。若未設定alarm,則返回0。
Example : 第一次等待1秒後觸發Timer,之後每隔2秒觸發一次。
#include <iostream>
#include <unistd.h>
#include <signal.h>
using namespace std;
void my_alarm_handler(int a)
{
cerr<<"my_alarm_handler"<<endl;
alarm(2);//重新設定
}
int main()
{
signal( SIGALRM, my_alarm_handler );
alarm(1);
while(1){}
return 0;
}
--------------------------------------------------------------------------------------
● setitimer
#include <sys/time.h>setitimer與getitimer提供了三種類別的Timer使用:
#define ITIMER_REAL 0
#define ITIMER_VIRTUAL 1
#define ITIMER_PROF 2
int getitimer(int which, struct itimerval *value);
int setitimer(int which, const struct itimerval *value,
struct itimerval *ovalue);
- ITIMER_REAL : 以系統真實的時間來計算,觸發時會送出SIGALRM。
- ITIMER_VIRTUAL : 只計算process真正在執行的時間(在User Mode的處理),觸發時會送出SIGVTALRM。
- ITIMER_PROF : 計算該process在User Mode與Kernel Mode的處理時間,觸發時送出SIGPROF。
struct itimerval {
struct timeval it_interval; /* next value : 下一次觸發所需的時間*/
struct timeval it_value; /* current value : 目前距離觸發時間點 剩餘的時間*/
};
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};setitimer由第二個參數value設定觸發的時間。第三個參數ovalue用來取得上一次 setitimer設定的itimerval值(此參數可以為NULL)。值得注意的是,根據itimerval裡變數的意義,當it_interval設定為0時,Timer只會觸發一次。而it_value設定為0時,代表Timer結束。
Return value : 如果成功則return 0,失敗則return -1。
Example : 第一次等待1秒後觸發Timer,之後每隔2秒觸發一次。
#include <iostream>
#include <sys/time.h>
#include <signal.h>
using namespace std;
void my_alarm_handler(int a)
{
cerr<<"test "<<endl;
}
int main(){
struct itimerval t;
t.it_interval.tv_usec = 0;
t.it_interval.tv_sec = 2;
t.it_value.tv_usec = 0;
t.it_value.tv_sec = 1;
if( setitimer( ITIMER_REAL, &t, NULL) < 0 ){
cerr<<"settimer error."<<endl;
return -1;
}
signal( SIGALRM, my_alarm_handler );
while(1){
sleep(2);
}
return 0;
}
● 根據以上,可知Linux內建的Timer還是有點簡陋,而且setitimer同一時間只能處理3個Timer,如果應用程式需要多個Timer的話,這個Linux內建的Timer可能就不敷需求了!