linux内核--定时器API

/** 定时器结构体
struct timer_list {
    ........
    unsigned long expires; --内核希望定时器执行的jiffies值
    void (*function)(unsigned long);  --定时器到时时执行的函数
    unsigned long data;  --传入执行函数的参数
*/
/** 该函数将墙钟时间转换为jiffies值
extern unsigned long mktime(const unsigned int year, const unsigned        
                                int mon, const unsigned int day, 
                                const unsigned int hour, 
                                const unsigned int min, 
                                const unsigned int sec)       
*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


static int year;
static int mon;
static int day;
static int hour;
static int min;
static int sec;
static long data;
static int flag = 0;
static int time;
static struct timer_list timer;

module_param(year, int, S_IRUGO);
module_param(mon, int, S_IRUGO);
module_param(day, int, S_IRUGO);
module_param(hour, int, S_IRUGO);
module_param(min, int, S_IRUGO);
module_param(sec, int, S_IRUGO);
module_param(data, long, S_IRUGO);
module_param(time, int, S_IRUGO);
module_param(flag, int, S_IRUGO);


void handler(unsigned long data)
{
    int i=0;
    for (i=0; i<10; i++)
    {
        printk(KERN_ALERT "%d ", i);
    }
    printk(KERN_ALERT "\n");
}

static int __init Example_init(void)
{

    unsigned long j = jiffies;

    printk(KERN_ALERT "Example_init.\n");

    init_timer(&timer);   //初始化结构体
    if (flag)
        timer.expires = mktime(year, mon, day, hour, min, sec);
    else
        timer.expires = j + time;
    timer.function = handler;
    timer.data = data;
    add_timer(&timer);  //向内核添加定时器

    return 0;
}

static void __exit Example_exit(void)
{
    printk(KERN_ALERT "Example_exit.\n");
    del_timer(&timer);  //删除定时器
    /**以下函数确保在函数返回时没有其他cpu在运行此定时器函数
     int del_timer_sync(struct timer_list *timer)
     */
    return;
}

MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Flying");

module_init(Example_init);
module_exit(Example_exit);

你可能感兴趣的:(Linux字符驱动)