首頁  >  文章  >  系統教程  >  定時器 Timer 在 Linux 下的多種應用方法及優缺點

定時器 Timer 在 Linux 下的多種應用方法及優缺點

WBOY
WBOY原創
2024-07-19 15:52:09853瀏覽

定时器 Timer 在 Linux 下的多种应用方法及优缺点

定時器Timer應用場景十分廣泛,在Linux下linux 應用定時器,有以下幾種方式:

1紅旗linux桌面版,使用sleep()和usleep()

其中sleep精度是一秒,usleep精度是1微妙,具體程式碼就不寫了。使用這些技巧缺點比較顯著,在Linux系統中,sleep類別函數無法保證精確度,尤其在系統負載比較大時,sleep通常還會有逾時現象。

2,使用訊號量SIGALRM+alarm()

這些方法的精度能達到一秒,其中藉助了*nix系統的訊號量機制,首先註冊訊號量SIGALRM處理函數,調用alarm(),設定定時寬度,程式碼如下:

#include 
#include 
void timer(int sig)
{
if(SIGALRM == sig)
{
printf("timern");
alarm(1); //we contimue set the timer
}
return ;
}
int main()
{
signal(SIGALRM, timer); //relate the signal and function
alarm(1); //trigger the timer
getchar();
return 0;
}

应用定时器设计电子钟_应用定时器2安卓版下载_linux 应用定时器

alarm方法儘管挺好,而且難以先高於一秒的精度。

3,使用RTC機制

RTC機制藉助系統硬體提供的RealTimeClock機制,透過讀取RTC硬體/dev/rtc,透過ioctl()設定RTC頻度,程式碼如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc, char* argv[])
{
unsigned long i = 0;
unsigned long data = 0;
int retval = 0;
int fd = open ("/dev/rtc", O_RDONLY);
if(fd < 0)
{
perror("open");
exit(errno);
}
/*Set the freq as 4Hz*/
if(ioctl(fd, RTC_IRQP_SET, 1) < 0)
{
perror("ioctl(RTC_IRQP_SET)");
close(fd);
exit(errno);
}
/* Enable periodic interrupts */
if(ioctl(fd, RTC_PIE_ON, 0) < 0)
{
perror("ioctl(RTC_PIE_ON)");
close(fd);
exit(errno);
}
for(i = 0; i < 100; i++)
{
if(read(fd, &data, sizeof(unsigned long)) < 0)
{
perror("read");
close(fd);
exit(errno);
}
printf("timern");
}
/* Disable periodic interrupts */
ioctl(fd, RTC_PIE_OFF, 0);
close(fd);
return 0;
}

這些方法比較便捷,借助了系統硬體提供的RTC,精度可調,而且特別高。

4,使用select()

這些方式在看APUE神書時侯聽到的,技巧比較小眾linux 應用定時器linux常用命令,透過使用select(),來設定定時器;原理借助select()方式的第5個參數,第一個參數設定為0,三個檔案描述子集都設定為NULL,第5個參數為時間結構體,程式碼如下:

#include 
#include 
#include 
#include 
/*seconds: the seconds; mseconds: the micro seconds*/
void setTimer(int seconds, int mseconds)
{
struct timeval temp;
temp.tv_sec = seconds;
temp.tv_usec = mseconds;
select(0, NULL, NULL, NULL, &temp);
printf("timern");
return ;
}
int main()
{
int i;
for(i = 0 ; i < 100; i++)
setTimer(1, 0);
return 0;
}

這些技巧精度才能達到微妙級別,網路上有好多基於select()的多執行緒定時器,說明select()穩定性還是十分好。

總結:假如對系統要求比較低,可以考慮使用簡單的sleep(),雖然一行程式碼能夠解決;假如係統對精度要求比較高,則可以考慮RTC機制和select()機制。

以上是定時器 Timer 在 Linux 下的多種應用方法及優缺點的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn