class_create的应用

本文介绍如何使用Linux内核提供的函数自动创建设备节点,包括class_create和device_create的使用方法及示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在刚开始写Linux设备驱动程序的时候,很多时候都是利用mknod命令手动创建设备节点,实际上Linux内核为我们提供了一组函数,可以用来在模块加载的时候自动在/dev目录下创建相应设备节点,并在卸载模块时删除该节点,当然前提条件是用户空间移植了udev。


内核中定义了struct class结构体,顾名思义,一个struct class结构体类型变量对应一个类,内核同时提供了class_create(…)函数,可以用它来创建一个类,这个类存放于sysfs下面,一旦创建好了这个类,再调用device_create(…)函数来在/dev目录下创建相应的设备节点。这样,加载模块的时候,用户空间中的udev会自动响应device_create(…)函数,去/sysfs下寻找对应的类从而创建设备节点。


注意,在2.6较早的内核版本中,device_create(…)函数名称不同,是class_device_create(…),所以在新的内核中编译以前的模块程序有时会报错,就是因为函数名称不同,而且里面的参数设置也有一些变化。


struct class和device_create(…) 以及device_create(…)都定义在/include/linux/device.h中,使用的时候一定要包含这个头文件,否则编译器会报错。 


在2.6.26.6内核版本中,struct class定义在头文件include/linux/device.h中:


/*
      * device classes
      */
    struct class {
      const char        *name;
      struct module     *owner;


  nbsp;struct kset         subsys;
      struct list_head         devices;
      struct list_head         interfaces;
      struct kset              class_dirs;
      struct semaphore sem;    /* locks children, devices, interfaces */
      struct class_attribute   *class_attrs;
      struct device_attribute      *dev_attrs;


  int (*dev_uevent)(struct device *dev, struct kobj_uevent_env *env);


  void (*class_release)(struct class *class);
      void (*dev_release)(struct device *dev);


  int (*suspend)(struct device *dev, pm_message_t state);
      int (*resume)(struct device *dev);


};


class_create(…)在/drivers/base/class.c中实现: 
     /**
    * class_create - create a struct class structure
    * @owner: pointer to the module that is to "own" this struct class
    * @name: pointer to a string for the name of this class.
    *
    * This is used to create a struct class pointer that can then be used
    * in calls to device_create().
    *
    * Note, the pointer created here is to be destroyed when finished by
    * making a call to class_destroy().
    */
   struct class *class_create(struct module *owner, const char *name)
   {
      struct class *cls;
      int retval;
      cls = kzalloc(sizeof(*cls), GFP_KERNEL);
      if (!cls) {
           retval = -ENOMEM;
           goto error;
      }


  cls->name = name;
      cls->owner = owner;
      cls->class_release = class_create_release;


  retval = class_register(cls);
      if (retval)
           goto error;


  return cls;


error:
      kfree(cls);
      return ERR_PTR(retval);
    }
    第一个参数指定类的所有者是哪个模块,第二个参数指定类名。 
    在class.c中,还定义了class_destroy(…)函数,用于在模块卸载时删除类。 


device_create(…)函数在/drivers/base/core.c中实现: 
    /**
     * device_create - creates a device and registers it with sysfs
     * @class: pointer to the struct class that this device should be registered to
     * @parent: pointer to the parent struct device of this new device, if any
     * @devt: the dev_t for the char device to be added
     * @fmt: string for the device's name
     *
     * This function can be used by char device classes. A struct device
     * will be created in sysfs, registered to the specified class.
     *
     * A "dev" file will be created, showing the dev_t for the device, if
     * the dev_t is not 0,0.
     * If a pointer to a parent struct device is passed in, the newly created
     * struct device will be a child of that device in sysfs.
     * The pointer to the struct device will be returned from the call.
     * Any further sysfs files that might be required can be created using this
     * pointer.
     *
     * Note: the struct class passed to this function must have previously
     * been created with a call to class_create().
     */
    struct device *device_create(struct class *class, struct device *parent,
                        dev_t devt, const char *fmt, ...)
    {
         va_list vargs;
         struct device *dev;


     va_start(vargs, fmt);
         dev = device_create_vargs(class, parent, devt, NULL, fmt, vargs);
         va_end(vargs);
         return dev;
    }


第一个参数指定所要创建的设备所从属的类,第二个参数是这个设备的父设备,如果没有就指定为NULL,第三个参数是设备号,第四个参数是设备名称,第五个参数是从设备号。 


下面以一个简单字符设备驱动来展示如何使用这几个函数 
    #include <linux/module.h>
    #include <linux/kernel.h>
    #include <linux/init.h>
    #include <linux/fs.h>
    #include <linux/cdev.h>
    #include <linux/device.h>


MODULE_LICENSE ("GPL");


int hello_major = 555;
    int hello_minor = 0;
    int number_of_devices = 1;


struct cdev cdev;
    dev_t dev = 0;


struct file_operations hello_fops = {
      .owner = THIS_MODULE
    };


static void char_reg_setup_cdev (void)
    {
       int error, devno = MKDEV (hello_major, hello_minor);
       cdev_init (&cdev, &hello_fops);
       cdev.owner = THIS_MODULE;
       cdev.ops = &hello_fops;
       error = cdev_add (&cdev, devno , 1);
       if (error)
           printk (KERN_NOTICE "Error %d adding char_reg_setup_cdev", error);


}


struct class *my_class;


static int __init hello_2_init (void)
    {
       int result;
       dev = MKDEV (hello_major, hello_minor);
       result = register_chrdev_region (dev, number_of_devices, "hello");
       if (result<0) {
           printk (KERN_WARNING "hello: can't get major number %d/n", hello_major);
           return result;
     }


 char_reg_setup_cdev ();


 /* create your own class under /sysfs */
     my_class = class_create(THIS_MODULE, "my_class");
     if(IS_ERR(my_class)) 
     {
          printk("Err: failed in creating class./n");
          return -1; 
      } 


  /* register your own device in sysfs, and this will cause udev to create corresponding device node */
      device_create( my_class, NULL, MKDEV(hello_major, 0), "hello" "%d", 0 );


  printk (KERN_INFO "Registered character driver/n");
      return 0;
    }


static void __exit hello_2_exit (void)
    {
       dev_t devno = MKDEV (hello_major, hello_minor);


       cdev_del (&cdev);


   device_destroy(my_class, MKDEV(adc_major, 0));         //delete device node under /dev
       class_destroy(my_class);                               //delete class created by us


   unregister_chrdev_region (devno, number_of_devices);


   printk (KERN_INFO "char driver cleaned up/n");
    }


module_init (hello_2_init);
    module_exit (hello_2_exit);


这样,模块加载后,就能在/dev目录下找到hello0这个设备节点了。

<think>我们正在讨论Linux内核驱动开发中的device_createclass_create函数。根据用户需求,我们需要解释这两个函数之间的关系,并说明它们在设备驱动开发中的作用。首先,我们回顾一下Linux设备模型的基本概念。在Linux内核中,设备通常组织在类(class)之下,类是一个逻辑上的集合,用于管理一组具有相似功能的设备。例如,所有字符设备可能属于同一个类。类在sysfs文件系统中表现为一个目录,其中包含该类下的所有设备。现在,我们具体分析这两个函数:1.class_create:这个函数用于创建一个新的设备类。它会返回一个指向structclass的指针,这个结构体代表一个设备类。在sysfs中,这个类将出现在/sys/class/目录下。例如,创建一个名为"myclass"的类:```cstructclass*my_class=class_create(THIS_MODULE,"myclass");```2.device_create:这个函数用于在指定的类下创建设备节点。它会在sysfs中创建对应的设备项,并在/dev目录下创建设备节点(如果使用了udev或devtmpfs)。这个函数需要传入一个类指针(由class_create返回)以及其他参数,如父设备、设备号、设备名称等。例如,在my_class类下创建一个名为"mydevice"的设备:```cdevice_create(my_class,NULL,devt,NULL,"mydevice");```它们之间的关系是:-class_create必须先于device_create调用,因为创建具体的设备节点需要指定其所属的类。-一个类可以包含多个设备,因此可以多次调用device_create在同一个类下创建多个设备节点。-当设备被移除时,需要先调用device_destroy删除设备节点,然后再调用class_destroy销毁类。这种机制的好处是:-提供了统一的设备管理视图(通过sysfs)。-方便用户空间工具(如udev)根据设备类来设置设备节点的权限、创建符号链接等。因此,在设备驱动开发中,我们通常会在模块初始化函数中调用class_create来创建一个类,然后在探测(probe)函数中为每个检测到的设备调用device_create。在模块退出函数中,我们会移除所有设备并销毁类。下面是一个简单的示例代码片段:```c#include<linux/device.h>staticstructclass*my_class;staticdev_tdev_num;staticint__initmy_init(void){//分配设备号alloc_chrdev_region(&dev_num,0,1,"mydevice");//创建设备类my_class=class_create(THIS_MODULE,"myclass");if(IS_ERR(my_class)){//错误处理returnPTR_ERR(my_class);}//在类下创建设备device_create(my_class,NULL,dev_num,NULL,"mydevice");return0;}staticvoid__exitmy_exit(void){//销毁设备device_destroy(my_class,dev_num);//销毁类class_destroy(my_class);//释放设备号unregister_chrdev_region(dev_num,1);}module_init(my_init);module_exit(my_exit);```在这个示例中,我们首先分配了一个设备号,然后创建了一个名为"myclass"的类,最后在这个类下创建了一个名为"mydevice"的设备。在模块卸载时,我们按相反的顺序销毁设备和类。通过这样的方式,设备模型在sysfs中会表现为:-/sys/class/myclass/-/sys/class/myclass/mydevice同时,在/dev目录下会有一个设备节点(例如/dev/mydevice)。总结:class_create用于创建一个设备类,而device_create则在该类下创建设备节点。它们共同构成了Linux设备模型中的层次结构,使得设备管理更加有序和一致。相关问题:1.在Linux设备驱动中,class_create和device_create函数失败时应该如何处理?2.除了class_create和device_create,还有哪些函数用于管理Linux设备模型?3.在sysfs中,设备和类的属性文件是如何创建和管理的?</think>### Linux内核中`device_create`与`class_create`的关系 在Linux设备驱动开发中,`class_create`和`device_create`是构建设备模型的核心函数,它们共同实现**sysfs设备树**的层次化组织,关系如下: #### 1. **`class_create`:创建设备类** - **作用**:在`/sys/class/`目录下创建**逻辑设备类别**(如`leds`, `input`等) - **功能**: - 定义一类具有共同属性的设备(如所有LED设备) - 生成类目录:`/sys/class/<class_name>` - **典型用法**: ```c struct class *my_class = class_create(THIS_MODULE, "mydev_class"); ``` #### 2. **`device_create`:创建设备节点** - **作用**:在指定类下创建**具体设备实例** - **依赖**:必须基于`class_create`返回的类指针 - **功能**: - 在`/sys/class/<class_name>/`下生成设备目录(如`mydev_device`) - 自动在`/dev/`生成设备节点文件(需配合`dev_t`设备号) - **典型用法**: ```c device_create(my_class, NULL, devt, NULL, "mydev_device"); ``` #### 3. 协作流程(代码示例) ```c // 1. 创建设备类 struct class *dev_class = class_create(THIS_MODULE, "my_class"); // 2. 分配设备号 dev_t dev_num; alloc_chrdev_region(&dev_num, 0, 1, "mydev"); // 3. 在类下创建设备节点 struct device *dev = device_create(dev_class, NULL, dev_num, NULL, "mydev0"); // 4. 注销时反向操作 device_destroy(dev_class, dev_num); // 先删除设备 class_destroy(dev_class); // 再销毁类 ``` #### 4. 关键关系总结 | 特性 | `class_create` | `device_create` | |---------------------|-----------------------------------|-------------------------------------| | **目标对象** | 设备类别(抽象概念) | 具体设备实例 | | **sysfs位置** | `/sys/class/<class_name>` | `/sys/class/<class_name>/<device>` | | **依赖关系** | 无需前置条件 | 必须基于已存在的类 | | **用户空间可见性** | 类目录 | `/dev/`下设备节点 + 类内设备属性 | #### 5. 实际效果演示 执行后sysfs结构: ``` /sys/class/ └── my_class/ ← class_create创建 ├── mydev0/ ← device_create创建 │ ├── dev # 设备号属性 │ └── power/ # 电源管理 └── ... # 可添加更多设备 ``` 同时`/dev/mydev0`设备节点被自动生成(通过udev机制)。 > **设计哲学**:这种分层模型实现了: > 1. **统一管理**:同类别设备共享操作接口 > 2. **动态扩展**:新设备加入无需修改类逻辑 > 3. **用户空间标准化**:应用通过sysfs统一访问设备属性[^1] --- ### 相关问题 1. 当`device_create`失败时应该如何处理已分配的资源和已创建的类? 2. 如何通过sysfs向用户空间暴露自定义设备属性? 3. 在热插拔场景中,`class_create`和`device_create`需要配合哪些其他内核API? [^1]: Linux设备模型的核心设计思想是通过sysfs实现用户空间对设备状态的标准化访问,类与设备的层级关系是此模型的关键实现机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值