日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

Linux 内核定时器使用 一 低精度定时器

發布時間:2025/4/5 linux 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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; //時間,通常精度在毫秒級別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);//定時器靜態初始化 #define DEFINE_TIMER(_name, _function, _expires, _data)//添加定時器 void add_timer(struct timer_list *timer);//刪除定時器 int del_timer(struct timer_list * timer);//和上面類似,但該函數可確保在返回時沒有任何CPU在運行定時器函數 int del_timer_sync(struct timer_list *timer);//修改定時器 int mod_timer(struct timer_list *timer, unsigned long expires);//檢查定時器是否正在被調度運行 int timer_pending(const struct timer_list * timer);

下面給出定時器使用的小栗子,定時器以斐波那契數列為參數,當定時時間達到13秒時自動退出:

/** Description : 內核定時器demo* Author : mason* Date : 201808*/#include <linux/timer.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h>static unsigned long data; struct timer_list demo_timer;/* 斐波那契數列 */ unsigned long fibonacci(unsigned long data) {if (data == 1 || data == 2){return 1;}else{return fibonacci(data-1) + fibonacci(data-2);} }/* 定時器回調函數 */ void timer_handler(unsigned long arg) {unsigned long intv;printk("current fibonacci is : %lu \r\n", arg);if (arg == 13) {printk("Game Over Bye\r\n");del_timer(&demo_timer);return ;}else{data++;intv = fibonacci(data);/* HZ單位為秒 */demo_timer.expires = intv * HZ + jiffies;demo_timer.data = intv;/* 重新添加定時器 */add_timer(&demo_timer);return;} }static int __init timer_demo_init(void) {printk("Hello timer\r\n");data = 1;/* 定時器初始化 */init_timer(&demo_timer);demo_timer.expires = data * HZ + jiffies;demo_timer.data = data;demo_timer.function = timer_handler; add_timer(&demo_timer);return 0; }static void __exit timer_demo_exit(void) {printk("Bye timer\r\n");return ; }module_init(timer_demo_init) module_exit(timer_demo_exit) MODULE_AUTHOR("mason"); MODULE_DESCRIPTION("netlink kernel test"); MODULE_LICENSE("GPL");

Makefile:

obj-m := timer_demo.oPWD := $(shell pwd) KERNEL_DIR := "/usr/src/linux-headers-"$(shell uname -r)/modules:@$(MAKE) -C $(KERNEL_DIR) M=$(PWD) modules clean:@rm -rf *.ko *.o *.mod.c *symvers *order .nl* .tmp*

內核版本 : 3.4.39

運行截圖:

參考資料 :

1. 《LInux 設備驅動程序第三版》

2. 《深入理解Linux內核》

總結

以上是生活随笔為你收集整理的Linux 内核定时器使用 一 低精度定时器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。