原文地址: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