Linux內核中提供了timer使用的API,做一個簡單的記要。
1. 包含的頭文件:linux/timer.h
2. 數據類型:struct timer_list;
包含的主要成員:
a. data:傳遞到超時處理函數的參數,主要在多個定時器同時使用時,區別是哪個timer超時。
b. expires:定時器超時的時間,以linux的jiffies來衡量。
c. void (*function)(unsigned long):定時器超時處理函數。
- 1
- 2
- 3
- 4
- 5
3. 主要相關的API函數:
a. init_timer(struct timer_list*):定時器初始化函數;
b. add_timer(struct timer_list*):往系統添加定時器;
c. mod_timer(struct timer_list *, unsigned long jiffier_timerout):修改定時器的超時時間為jiffies_timerout;
d. timer_pending(struct timer_list *):定時器狀態查詢,如果在系統的定時器列表中則返回1,否則返回0;
e. del_timer(struct timer_list*):刪除定時器。
- 1
- 2
- 3
- 4
- 5
- 6
4. 時間與jiffies的轉換函數:
Linux系統中的jiffies類似于Windows里面的TickCount,它是定義在內核里面的一個全局變量,只是它的單位并不是秒或是毫秒。通常是250個jiffies為一秒,在內核里面可以直接使用宏定義:HZ。這里有幾個時間和jiffies的相互轉換函數:
unsigned int jiffies_to_msecs(unsigned long);
unsigned int jiffies_to_usecs(unsigned long);
unsigned long msecs_to_jiffies(unsigned int);
unsigned long usecs_to_jiffies(unsigned int);
- 1
- 2
- 3
- 4
- 5
- 6
5. 使用簡例:
步驟:init_timer->[timer.expires=? & timer.function=?]->add_timer->[mod_timer]->del_timer.
- 1
- 2
#include <linux/init.h>
#include <linux/module.h>
#include <linux/timer.h>
struct timer_list timer;void timer_handler(unsigned long data) {printk(KERN_INFO"timer pending:%d\n", timer_pending(&timer));mod_timer(&timer, jiffies+msecs_to_jiffies(1000));printk(KERN_INFO"jiffies:%ld, data:%ld\n", jiffies, data);
}
int timer_init(void) {printk(KERN_INFO"%s jiffies:%ld\n", __func__, jiffies);printk(KERN_INFO"ji:%d,HZ:%d\n", jiffies_to_msecs(250), HZ);init_timer(&timer);timer.data = 45;timer.function = timer_handler;timer.expires = jiffies + HZ;add_timer(&timer);printk(KERN_INFO"timer pending:%d\n", timer_pending(&timer));return 0;
}void timer_exit(void) {printk(KERN_INFO"%s jiffies:%ld\n", __func__, jiffies);del_timer(&timer);
}module_init(timer_init);
module_exit(timer_exit);
MODULE_LICENSE("GPL");