1. 程式人生 > 其它 >01-02-2-字元裝置驅動程式之LED驅動程式_測試改進

01-02-2-字元裝置驅動程式之LED驅動程式_測試改進

技術標籤:01-linux驅動

改進:
1、自動分配主裝置號
2、自動建立裝置節點

自動分配主裝置號

只要register_chrdev函式第一個引數為0,返回值就是自動分配的主裝置號

major = register_chrdev(0, "first_drv", &first_drv_fops); 

自動建立節點

單板根檔案系統由busybox建立,在busybox中有mdev機制,可以根據/sys/class下的資訊自動建立裝置節點
1)啟動mdev機制
cat /etc/init.d/rcS

echo /sbin/mdev > /proc/sys/kernel/hotplug

2)自動建立節點的程式碼

static struct class *firstdrv_class;
static struct class_device	*firstdrv_class_dev;

firstdrv_class = class_create(THIS_MODULE, "firstdrv");
firstdrv_class_dev = class_device_create(firstdrv_class, NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */

3)重新編譯,安裝驅動,生成/sys/class/firstdrv/xyz/dev檔案,包含該裝置節點的主裝置號,次裝置號資訊

252:0

4)mdev機制,會自動根據該資訊生成裝置節點

# ls -l /dev | grep xyz
crw-rw----    1 0        0        252,   0 Jan  1 01:12 xyz

完整程式碼

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include
<asm/irq.h>
#include <asm/io.h> #include <asm/arch/regs-gpio.h> #include <asm/hardware.h> static struct class* firstdrv_class; static struct class_device* firstdrv_class_dev; static int first_drv_open(struct inode* inode, struct file* file) { printk("first_drv_open\n"); return 0; } static ssize_t first_drv_write(struct file* file, const char __user* buf, size_t count, loff_t* ppos) { printk("first_drv_write\n"); return 0; } static struct file_operations first_drv_fops = { .owner = THIS_MODULE, /* 這是一個巨集,推向編譯模組時自動建立的__this_module變數 */ .open = first_drv_open, .write = first_drv_write, }; int major; static int first_drv_init(void) { // 第一個引數為0時,會自動分配主裝置號 major = register_chrdev(0, "first_drv", &first_drv_fops); // 註冊, 告訴核心 firstdrv_class = class_create(THIS_MODULE, "firstdrv"); firstdrv_class_dev = class_device_create(firstdrv_class, NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */ return 0; } static void first_drv_exit(void) { unregister_chrdev(major, "first_drv"); // 解除安裝 class_device_unregister(firstdrv_class_dev); class_destroy(firstdrv_class); } module_init(first_drv_init); module_exit(first_drv_exit); MODULE_LICENSE("GPL");