linux内核编程之内核定时器
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                linux内核编程之内核定时器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                【版權聲明:轉載請保留出處:blog.csdn.net/gentleliu。郵箱:shallnew*163.com】
 
Linux 內核所提供的用于操作定時器的數據結構和函數(位于 <linux/timer.h>)如下
struct timer_list {/** All fields that change during normal runtime grouped to the* same cacheline*/struct list_head entry; /* 定時器列表 */unsigned long expires; /* 期望定時器執行的jiffies值 */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 };
使用定時器必須初始化,使用函數
void init_timer(struct timer_list * timer);然后還需為定時器結構成員expires、function、data(需要的話)賦值。
使用如下函數注冊定時器:
void add_timer(struct timer_list * timer);這樣定時器將在expires之后執行函數function,不過此時只能執行一次,如果想在之后每個expires時間都執行function函數的話,需要在function函數里面修改定時器expires的值。使用如下函數修改:
int mod_timer(struct timer_list *timer, unsigned long expires);在定時器處理函數中,在做完相應的工作后,往往會延后 expires 并將定時器再次添加到內核定時器鏈表,以便定時器能再次被觸發。
一個示例如下:
#include <linux/module.h> #include <linux/init.h> #include <linux/version.h>#include <linux/timer.h> #include <linux/delay.h>struct timer_list sln_timer;void sln_timer_do(unsigned long l) {mod_timer(&sln_timer, jiffies + HZ);//HZ為1秒,在此時間之后繼續執行printk(KERN_ALERT"jiffies: %ld\n", jiffies);//簡單打印jiffies的值 }void sln_timer_set(void) {init_timer(&sln_timer);//初始化定時器sln_timer.expires = jiffies + HZ; //1s后執行sln_timer.function = sln_timer_do; //執行函數add_timer(&sln_timer); //向內核注冊定時器 }static int __init sln_init(void) {printk(KERN_ALERT"===%s===\n", __func__);sln_timer_set();return 0; }static void __exit sln_exit(void) {printk(KERN_ALERT"===%s===\n", __func__);del_timer(&sln_timer);//刪除定時器 }module_init(sln_init); module_exit(sln_exit);MODULE_LICENSE("GPL"); MODULE_AUTHOR("sln");
像定時器這種周期性的任務還可以使用延時工作隊列來實現。
給一個示例:
#include <linux/module.h> #include <linux/init.h> #include <linux/version.h>#include <linux/workqueue.h> #include <linux/delay.h>static struct workqueue_struct *sln_wq = NULL; static struct delayed_work sln_dwq;static void sln_do(struct work_struct *ws) {queue_delayed_work(sln_wq, &sln_dwq, 1000);printk(KERN_ALERT"jiffies: %ld\n", jiffies); }static int __init sln_init(void) {printk(KERN_ALERT"===%s===\n", __func__);sln_wq = create_workqueue("sln_work_queue");INIT_DELAYED_WORK(&sln_dwq, sln_do);queue_delayed_work(sln_wq, &sln_dwq, 0);return 0; }static void __exit sln_exit(void) {printk(KERN_ALERT"===%s===\n", __func__);cancel_delayed_work(&sln_dwq);flush_workqueue(sln_wq);destroy_workqueue(sln_wq); }module_init(sln_init); module_exit(sln_exit);MODULE_LICENSE("GPL"); MODULE_AUTHOR("allen");
總結
以上是生活随笔為你收集整理的linux内核编程之内核定时器的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 模板标签及模板的继承与引用
 - 下一篇: 跨站脚本专题 XSS