字符设备驱动_5:自动创建设备节点

本文档介绍了如何修改Linux字符设备驱动,使用`class_create()`和`device_create()`函数自动创建设备节点,而非手动通过`mknode`命令。示例代码展示了在驱动初始化时动态生成设备节点的过程,并实现了设备节点的正确操作。通过这些接口,可以更方便地管理设备节点。
摘要由CSDN通过智能技术生成

概述:前面写了驱动,都是手动通过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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值