日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

二十二、linux定时器

發(fā)布時(shí)間:2025/4/5 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二十二、linux定时器 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、Linux 定時(shí)器介紹

?????????在 Linux 內(nèi)核中, 定時(shí)器叫做內(nèi)核定時(shí)器, 內(nèi)核定時(shí)器用于控制某個(gè)函數(shù), 也就是定時(shí)器將要處理的函數(shù)在未來的某個(gè)特定的時(shí)間內(nèi)執(zhí)行。 內(nèi)核定時(shí)器注冊(cè)的處理函數(shù)只執(zhí)行一次, 即不是循環(huán)執(zhí)行的。 定時(shí)器的使用范圍(延后執(zhí)行某個(gè)操作, 定時(shí)查詢某個(gè)狀態(tài); 前提是對(duì)時(shí)間要求不高的地方) 。

????????Hz: 系統(tǒng)時(shí)鐘通過 CONFIG_HZ 來設(shè)置, 范圍是 100-1000; HZ 決定使用中斷發(fā)生的頻率。 如果就沒有定義的話, 默認(rèn)是 100, 例: 1/200 = 5ms, 說明 4412 中是 5ms 產(chǎn)生一次時(shí)鐘中斷。內(nèi)核的全局變量 jiffies: (記錄內(nèi)核自啟動(dòng)來的節(jié)拍數(shù), 啟動(dòng)的時(shí)候初始化為 0, 內(nèi)核之啟動(dòng)以來, 產(chǎn)生的中斷數(shù)) 時(shí)鐘中斷, 每產(chǎn)生一個(gè)中斷, jiffies 就加 1。 可以用來計(jì)算流逝時(shí)間和時(shí)間管理, jiffies 除以Hz 得到內(nèi)核自啟動(dòng)以來的秒數(shù)。

二、數(shù)據(jù)類型:struct timer_list

struct timer_list {/** All fields that change during normal runtime grouped to the* same cacheline*/struct list_head entry;unsigned long expires;struct tvec_base *base;void (*function)(unsigned long);unsigned long data;int slack;#ifdef CONFIG_TIMER_STATSint start_pid;void *start_site;char start_comm[16]; #endif #ifdef CONFIG_LOCKDEPstruct lockdep_map lockdep_map; #endif };

包含的主要成員:

  • struct list_head entry 雙向鏈表

  • expires:定時(shí)器超時(shí)的時(shí)間,以linux的jiffies來衡量,記錄什么時(shí)候產(chǎn)生時(shí)鐘中斷。

  • struct tvec_base *base: 管理時(shí)鐘的結(jié)構(gòu)體

  • void (*function)(unsigned long):定時(shí)器超時(shí)處理函數(shù)。

  • data:傳遞到超時(shí)處理函數(shù)的參數(shù),主要在多個(gè)定時(shí)器同時(shí)使用時(shí),區(qū)別是哪個(gè)timer超時(shí)。

三、主要相關(guān)的API函數(shù)

init_timer(struct timer_list*):定時(shí)器初始化函數(shù); add_timer(struct timer_list*):往系統(tǒng)添加定時(shí)器; mod_timer(struct timer_list *, unsigned long jiffier_timerout):修改定時(shí)器的超時(shí)時(shí)間為jiffies_timerout; timer_pending(struct timer_list *):定時(shí)器狀態(tài)查詢,如果在系統(tǒng)的定時(shí)器列表中則返回1,否則返回0; del_timer(struct timer_list*):刪除定時(shí)器。

四、使用簡(jiǎn)例

#include "linux/module.h" #include "linux/timer.h" #include "linux/jiffies.h"struct timer_list demo_timer;static void time_func(unsigned long data) {printk("%s ,secs = %ld!\n",(char *)data,jiffies/HZ);mod_timer(&demo_timer,jiffies + 5*HZ); }static int __init mytimer_init(void) {printk("mytimer_init!\n");setup_timer(&demo_timer,time_func,(unsigned long) "demo_timer!");demo_timer.expires = jiffies + 1*HZ;add_timer(&demo_timer);return 0; }static void __exit mytimer_exit(void) {printk("mytimer_exit!\n");del_timer(&demo_timer); }module_init(mytimer_init); module_exit(mytimer_exit);MODULE_LICENSE("Dual BSD/GPL");

五、運(yùn)行結(jié)果

?

總結(jié)

以上是生活随笔為你收集整理的二十二、linux定时器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。