kk Blog —— 通用基础

date [-d @int|str] [+%s|"+%F %T"]

高精度定时器示例

http://blog.chinaunix.net/uid-361890-id-257337.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/hrtimer.h>
#include <linux/jiffies.h>

static struct hrtimer timer;
ktime_t kt;

static enum hrtimer_restart hrtimer_handler(struct hrtimer *timer)
{
	//kt = ktime_set(1, 10);
	printk(" ------ I am in hrtimer -----\n");
	hrtimer_forward(timer, timer->base->get_time(), kt);
	return HRTIMER_RESTART;
}

static int __init test_init(void)
{
	pr_info("timer resolution: %lu\n", TICK_NSEC);
	kt = ktime_set(1, 10); /* 1 sec, 10 nsec */
	hrtimer_init(&timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
	//hrtimer_set_expires(&timer, kt);
	hrtimer_start(&timer, kt, HRTIMER_MODE_REL);
	timer.function = hrtimer_handler;

	printk("\n-------- test start ---------\n");
	return 0;
}

static void __exit test_exit(void)
{
	hrtimer_cancel(&timer);
	printk("-------- test over ----------\n");
	return;
}

MODULE_LICENSE("GPL");

module_init(test_init);
module_exit(test_exit);

编译:

1
2
3
4
5
6
7
8
9
10
name = test.o
obj-m := $(name)

KERNELDIR := /home/tangyt/tmp/linux-2.6-cloud.p1020/

default:
	make -C $(KERNELDIR) M=$(shell pwd) modules

clean:
	make -C $(KERNELDIR) M=$(shell pwd) clean