Linux下hrtimer demo

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 */
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值