原文地址:Kernel Module实战指南(三):编写字符型设备node
咱们今天编写第一个Linux Kernel Module的驱动程序:一个字符型设备驱动。经过简单的open(), release(), read(), write(),你将理解驱动程序的编程方法。linux
在Linux中,一切都是文件,设备驱动也绝不例外。文件的定义在linux/fs.h中,目前咱们只须要关注file_operations结构。编程
struct file_operations { ... ssize_t(*read) (struct file *, char __user *, size_t, loff_t *); ssize_t(*write) (struct file *, const char __user *, size_t, loff_t *); int (*open) (struct inode *, struct file *); int (*release) (struct inode *, struct file *); ... };
上面四个回调函数,是咱们目前须要关心的,后面的例子也只会使用这四个回调函数。
编写咱们本身的设备驱动程序,须要根据需求实现file_operations结构中的回调函数,而后将驱动经过register_chrdev()注册到内核中便可。函数
#include <asm/uaccess.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> int init_module(void); void cleanup_module(void); static ssize_t device_read(struct file *, char *, size_t, loff_t *); static ssize_t device_write(struct file *, const char *, size_t, loff_t *); static int device_open(struct inode *, struct file *); static int device_release(struct inode *, struct file *); // 咱们的设备名字 #define DEVICE_NAME "csprojectedu" static int major_version; static int device_is_open = 0; static char msg[1024]; static char *pmsg; // 定义设备容许的操做,这里只容许read(), write(), open(), release() static struct file_operations fops = { .read = device_read, .write = device_write, .open = device_open, .release = device_release }; // 模块注册函数 int init_module() { // 将咱们定义的设备操做的结构体fops注册到内核中 major_version = register_chrdev(0, DEVICE_NAME, &fops); if (major_version < 0) { printk(KERN_ALERT "Register failed, error %d.\n", major_version); return major_version; } // 打印设备名称和版本号,稍后咱们会利用这个来挂在模块到/dev/csprojectedu printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, major_version); return 0; } // 模块退出函数 void cleanup_module() { unregister_chrdev(major_version, DEVICE_NAME); } // 处理读模块的逻辑,能够经过cat /dev/csprojectedu 来简单的读取模块 static ssize_t device_read(struct file *filp, char *buffer, size_t length, loff_t *offset) { int bytes = 0; if (*pmsg == 0) { return 0; } while (length && *pmsg) { put_user(*(pmsg++), buffer++); length--; bytes++; } return bytes; } // 处理写模块的逻辑,咱们目前不支持 static ssize_t device_write(struct file *filp, const char *buff, size_t length, loff_t *offset) { return -EINVAL; } // 处理打开模块的逻辑 static int device_open(struct inode *inode, struct file *file) { static int counter = 0; if (device_is_open) { return -EBUSY; } device_is_open = 1; sprintf(msg, "Device open for %d times.\n", ++counter); pmsg = msg; try_module_get(THIS_MODULE); return 0; } // 处理释放/关闭模块的逻辑 static int device_release(struct inode *inode, struct file *file) { device_is_open = 0; module_put(THIS_MODULE); return 0; }
Makefile同以前的同样就好code
$ make $ sudo insmod csprojectedu.ko $ dmesg [115465.083271] 'mknod /dev/csprojectedu c 250 0'. $ sudo mknod /dev/csprojectedu c 250 0 $ cat /dev/csprojectedu Device open for 1 times. $ cat /dev/csprojectedu Device open for 2 times. $ sudo rm /dev/csprojectedu $ sudo rmmod csprojectedu.ko
经过编写一个简单的字符型设备驱动,咱们了解了Linux Kernel Module在驱动程序方面的应用。get