概述:前面写了驱动,都是手动通过mknode命令创建的设备节点,使用自动创建的方法实现设备节点创建。
基于之前的《字符设备驱动_3:register_chrdev_region() 简单字符设备驱动的实现》的代码进行更改,实现自动创建设备节点。
1. 程序更改
diff --git a/drivers/rivotek/char_3.c b/drivers/rivotek/char_3.c
index cdfdbb3b..cb7f6b32 100644
--- a/drivers/rivotek/char_3.c
+++ b/drivers/rivotek/char_3.c
@@ -4,6 +4,7 @@
#include <linux/cdev.h>
#include <linux/slab.h>
#include <linux/fs.h>
+#include <linux/device.h>
#define CDE_NAME "Rivotek_cdev"
@@ -15,6 +16,7 @@ struct my_char_dev
unsigned int mio; //<B4><CE><C9>豸<BA><C5>
unsigned int count;
struct cdev *cdev;
+ struct class *rivotek_class;
};
@@ -43,6 +45,7 @@ static const struct file_operations lcdev_fops = {
static int __init char_test_init(void)
{
int ret;
+ int i = -1;
lcdev = kmalloc(sizeof(struct my_char_dev), GFP_KERNEL);
@@ -54,8 +57,8 @@ static int __init char_test_init(void)
printk(KERN_ALERT"kmalloc ok \n");
lcdev->maj = 252;
- lcdev->mio = 2;
- lcdev->count = 1;
+ lcdev->mio = 0;
+ lcdev->count = 3;
ret = register_chrdev_region(MKDEV(lcdev->maj,lcdev->mio), lcdev->count, "chartest");
@@ -76,6 +79,17 @@ static int __init char_test_init(void)
goto add_fail;
printk(KERN_ALERT"maj: %d ,mio:%d\n", lcdev->maj, lcdev->mio);
+
+ lcdev->rivotek_class = class_create(THIS_MODULE, "Rivotek");
+ if (IS_ERR(lcdev->rivotek_class))
+ return;
+ for(i = 0; i < lcdev->count; i++)
+ {
+ char buf[16];
+ sprintf(buf, "Rivotek_%d", i);
+ device_create(lcdev->rivotek_class, NULL, MKDEV(lcdev->maj, i), NULL, buf);
+ memset(buf, 0, sizeof(buf));
+ }
return 0;
2. 实现的效果
安装驱动后,设备节点生成。
操作节点,符合程序设计。
3. 总结
使用接口函数
class_create()
device_create()