Linux裝置驅動開發入門--簡單的字元裝置驅動程式框架
阿新 • • 發佈:2021-07-14
字元裝置:字元裝置是指只能按照順序一個字接一個位元組讀寫的裝置,例如滑鼠、鍵盤、串列埠、LED等。
字元裝置驅動程式框架:模組載入函式、模組解除安裝函式、open函式、寫函式、讀函式、release函式、file_operations初始化函式
一、模組載入函式
一個簡單的模組載入函式需要申請裝置號,註冊裝置號,和註冊裝置。
#include <linux/kernel.h> #include <linux/module.h> #include <linux/cdev.h> #include <linux/fs.h> #include <asm/uaccess.h> #include<linux/fcntl.h> #define HELLO_MAJOR 250 //巨集定義hello裝置主裝置號 #define HELLO_MINOR 0 //次裝置號 #define DEV_NAME "Hello_Word" //裝置名 #define DEV_COUNT 1 //需要申請的連續裝置號的個數 dev_t dev_from; //定義dev_t型別的變數,定義裝置號的範圍的起始值, 記錄申請後的裝置號 //初始化 file_operations成員 struct file_operations hello_fops={ .owner= THIS_MODULE, .open = hello_open, //開啟裝置函式 .write = hello_write, //寫裝置函式 .read = hello_read, //讀裝置函式 .release = hello_release, //釋放裝置函式 .ioctl = hello_ioctl, //控制函式 }; //定義了一個字元裝置驅動hello的結構體,cdev結構體包含了很多成員,用於描述字元裝置,而hello_cdev是cdev型別結構體struct cdev hello_cdev(void); //載入函式 int __init hello_init(void){ int ret;//標誌位,用於檢測裝置號是否申請成功 //將主裝置號和次裝置號轉換成dev_t型別 dev_from = MKDEV(HELLO_MAJOR,HELLO_MINOR); //靜態申請裝置號,register_chrdev_region(dev_t, unsigned count,const char *name); ret = register_chrdev_region(dev_from, DEV_COUNT, DEV_NAME); if (ret < 0) { //動態申請裝置號alloc_chrdev_region(dev_t *dev,unsigned baseminor,unsigned count,const char *name) ret = alloc_chrdev_region(dev_from, HELLO_MINOR, DEV_COUNT,DEV_NAME); if (ret < 0){ printk("alloc_chrdev_region fail!!!\n"); return -EFAULT; } } printk("major = %d, minor = %d\n",MAJOR(dev_from),MINOR(dev_from)); //初始化裝置 cdev_init(&hello_cdev, &hello_fops); hello_cdev.owner = THIS_MODULE; //是驅動程式屬於該模組 ret = cdev_add(&hello_code,dev_from,DEV_COUNT);//註冊字元裝置 if (ret < 0){ printk("cdev_add fail !!!\n"); return -EFAULT; }else printk("cdev_add sucess!!!\n"); printk("hello_init!!!\n"); return 0; } module_init(hello_init);//模組載入 MODULE_LICENSE("GPL");
二、解除安裝函式
void __exit hello_exit(void) { printk(" hello_exit!!!\n"); cdev_del(&hello_cdev); printk(" cdev_del!!!\n"); unregister_chrdev_region(dev_from,DEV_COUNT); printk(" unregister_chrdev_region!!!\n"); } module_exit(hello_exit);