码迷,mamicode.com
首页 > 其他好文 > 详细

内核中的定时器

时间:2015-10-22 13:57:56      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>

MODULE_LICENSE("Duall BSD/GPL");

/* HZ表示1秒中振动的次数
 * 1秒钟产生的jiffies数量
 */
#define FAST_INTERVAL 1*HZ  

static struct timer_list led_slow_timer;


static void handler_timer(unsigned long speed)
{

    if(speed) {
        printk(KERN_DEBUG "speed1...");
    } else {
        printk(KERN_DEBUG "speed2...");
    }

    /* 内核定时器设置之后只执行一次,要循环执行,需要再次启动启动器 */
    led_slow_timer.expires=jiffies+FAST_INTERVAL;
    led_slow_timer.data = !speed;
    add_timer(&led_slow_timer);
}

static int __init timer_init(void)
{
    printk(KERN_ALERT "hello, kitty\n");

    init_timer(&led_slow_timer);
    /* 由于可能多个定时器调用一个函数,
     * 为了使得这个函数能够区分不同的定时器,
     * 通过在结构中data来标识这个定时器,
     * 并且通过调用 function(data)使得function能区分它们,
     * 也就是 data起到ID的作用
     */
    led_slow_timer.data=1;
    /* 0.5秒定时一次 */
    /* jiffies用于记录当前的时间,这里表示在当期那时间之后的FAST_INTERVAL调用定时器函数 */
    led_slow_timer.expires=jiffies+FAST_INTERVAL;
    /* 定时器调用的函数 */
    led_slow_timer.function = handler_timer;
    add_timer(&led_slow_timer);
    return 0;
}

static void __exit timer_exit(void)
{
    printk(KERN_ALERT "goodbye, kitty\n");
    /* 退出的时候需要关闭定时器,否则内核会出现错误
     * 虽然定时器超时会自动从time_list链表中删除,
     * 但是这个函数在定时器处理函数中循环启动定时器
     * 需要手动进行关闭
     */
    del_timer(&led_slow_timer);
}

module_init(timer_init);
module_exit(timer_exit);

编程模块,安装之后,查看定时器中的输出。

dmesg | tail -10

 

内核中的定时器

标签:

原文地址:http://www.cnblogs.com/helloworldtoyou/p/4900548.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!