(linux自学笔记)linux内核定时器的使用
原文地址:
http://www.cnblogs.com/hebaichuanyeah/
很显然linux的内核定时器基于时钟节拍(和ucos一样)。ucos的时钟节拍可由void OS_CPU_SysTickInit (INT32U cnts)函数设置。在linux中,时钟节拍在param.h中定义。
timer驱动程序
#include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/poll.h> #include <linux/irq.h> #include <asm/irq.h> #include <linux/interrupt.h> #include <asm/uaccess.h> #include <mach/regs-gpio.h> #include <mach/hardware.h> #include <linux/platform_device.h> #include <linux/cdev.h> #include <linux/miscdevice.h> #include <linux/sched.h> #include <linux/gpio.h> #include <mach/gpio-bank-n.h> #define DEVICE_NAME "timer_device" #define DEVICE_MAJOR 240 struct timer_list time_char_device; void timer_handle(void) { //改变定时器值 mod_timer(&time_char_device,jiffies+HZ); printk("<0>timer handle\n"); } static int s3c6410_timer_open(struct inode *inode, struct file *file) { //初始化 init_timer(&time_char_device); //中断处理函数 time_char_device.function = &timer_handle; //定时器值 time_char_device.expires = jiffies+HZ; //加入定时器 add_timer(&time_char_device); return 0; } static int s3c6410_timer_close(struct inode *inode, struct file *file) { //删除定时器 del_timer(&time_char_device); return 0; } static struct file_operations timer_device_fops = { .owner = THIS_MODULE, .open = s3c6410_timer_open, .release = s3c6410_timer_close, }; static int __init timer_device_init(void) { int ret; printk ("<0>timer init\n"); //注册字符设备 ret = register_chrdev(DEVICE_MAJOR,DEVICE_NAME,&timer_device_fops); if (ret <0) { printk ("<0>register %s char dev error\n","timer"); return -1; } printk ("<0>success\n"); return 0; } static void __exit timer_device_exit(void) { //注销设备 unregister_chrdev(DEVICE_MAJOR,DEVICE_NAME); printk ("<0>module exit\n"); } module_init(timer_device_init); module_exit(timer_device_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("hebaichuan");
测试程序
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> #define key_exit 5 int main(int argc, char **argv) { int fd; fd = open("/dev/timer_device",0); if(fd<0) { printf("open devie error\n"); return -1; } sleep(10); close(fd); return 0; }
程序运行结果