Download this MP3 - (Right Click)
伴着音乐开始Linux设备驱动之旅,接下来几篇日志都将记录“字符设备驱动程序”的编写与测试。
我选择边贴代码边说明的方式来进行分析设计我们的驱动程序,因为这样比较明确清楚。
自定义头文件demo.h如下:
#ifndef _DEMO_H_ #define _DEMO_H_ #include <linux/ioctl.h> /* needed for the _IOW etc stuff used later */ /******************************************************** * Macros to help debugging ********************************************************/ #undef PDEBUG /* undef it, just in case */ #ifdef DEMO_DEBUG #ifdef __KERNEL__ # define PDEBUG(fmt, args...) printk( KERN_DEBUG "DEMO: " fmt, ## args) #else//usr space # define PDEBUG(fmt, args...) fprintf(stderr, fmt, ## args) #endif #else # define PDEBUG(fmt, args...) /* not debugging: nothing */ #endif #undef PDEBUGG #define PDEBUGG(fmt, args...) /* nothing: it's a placeholder */ //设备号 #define DEMO_MAJOR 224 #define DEMO_MINOR 0 #define COMMAND1 1 #define COMMAND2 2 //设备结构 struct DEMO_dev { struct cdev cdev; /* Char device structure */ }; //函数申明 ssize_t DEMO_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos); ssize_t DEMO_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos); loff_t DEMO_llseek(struct file *filp, loff_t off, int whence); int DEMO_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg); #endif /* _DEMO_H_ */
这里面比较需要说明的是
1: #define DEMO_MAJOR 224
2: #define DEMO_MINOR 0
这里分别为主设备号、次设备号的定义。至于主次设备号的用处一会在源代码里面解释,这里提醒一下。
下面有很多的函数声明,这些函数是写驱动程序都应该有的,接下来解释具体实现。
下面为源文件demo.c
1: #include <linux/module.h>
2: #include <linux/kernel.h>
3: #include <linux/fs.h>
4: #include <linux/errno.h>
5: #include <linux/types.h>
6: #include <linux/fcntl.h>
7: #include <linux/cdev.h>
8: #include <linux/version.h>
9: #include <linux/vmalloc.h>