Kernel有两种定时器,一种是传统的低精度定时器timer,另一种是高精度定时器hrtimer。先来看下hrtimer的使用
#include <linux/module.h>
#include <linux/hrtimer.h>
#include <linux/fs.h>
#include <linux/ktime.h>
#include <linux/miscdevice.h>
#include <linux/device.h>
unsigned int timer_count=0;
struct hrtimer hrtimer_test;
static enum hrtimer_restart hrtimer_fun(struct hrtimer *timer){
ktime_t tick_period = ktime_set(1,0);
printk("timer_count=%d\n",timer_count++);
if(timer_count==500){
return HRTIMER_NORESTART;
}
else{
hrtimer_forward(timer,ktime_get(),tick_period);
return HRTIMER_RESTART;
}
}
struct miscdevice hrtimer_test_dev = {
.minor = MISC_DYNAMIC_MINOR,
.name = "hrtimer_test",
};
static ssize_t test_show(struct device *dev,struct device_attribute *attr, char *buf){
return 0;
}
static ssize_t test_store(struct device *dev,struct device_attribute *attr,const char *buf, size_t count){
hrtimer_cancel(&hrtimer_test);
return count;
}
static DEVICE_ATTR(test, S_IRUSR|S_IRGRP|S_IWUSR,test_show,test_store);
static int __init hrtimer_test_init(void){
int ret;
ret = misc_register(&hrtimer_test_dev);
hrtimer_init(&hrtimer_test, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
hrtimer_test.function = hrtimer_fun;
hrtimer_start(&hrtimer_test,ms_to_ktime(20), HRTIMER_MODE_REL);
ret = device_create_file(hrtimer_test_dev.this_device, &dev_attr_test);
return 0;
}
static void __exit hrtimer_test_exit(void){
hrtimer_cancel(&hrtimer_test);
misc_deregister(&hrtimer_test_dev);
}
module_init(hrtimer_test_init);
module_exit(hrtimer_test_exit);
MODULE_AUTHOR("hrtimer<hrtimer@hrtimer.cc>");
MODULE_LICENSE("GPL");
enum hrtimer_mode {
HRTIMER_MODE_ABS = 0x0, /* Time value is absolute */
HRTIMER_MODE_REL = 0x1, /* Time value is relative to now */
HRTIMER_MODE_PINNED = 0x02, /* Timer is bound to CPU */
HRTIMER_MODE_ABS_PINNED = 0x02,
HRTIMER_MODE_REL_PINNED = 0x03,
};
/*
* Return values for the callback function
*/
enum hrtimer_restart {
HRTIMER_NORESTART, /* Timer is not restarted */
HRTIMER_RESTART, /* Timer must be restarted */
};