cdev_add 和 device_create 函数之间的区别?

ove*_*ord 3 linux linux-device-driver linux-kernel

我是 linux 设备驱动程序开发的新手。我不明白 cdev_add 到底是做什么的。我查看了一些简单的字符设备驱动程序代码,我看到 cdev_add 和 device_create 函数一起使用。例如:

/* Create device class, visible in /sys/class */
dummy_class = class_create(THIS_MODULE, "dummy_char_class");
if (IS_ERR(dummy_class)) {
    pr_err("Error creating dummy char class.\n");
    unregister_chrdev_region(MKDEV(major, 0), 1);
    return PTR_ERR(dummy_class);
}

/* Initialize the char device and tie a file_operations to it */
cdev_init(&dummy_cdev, &dummy_fops);
dummy_cdev.owner = THIS_MODULE;
/* Now make the device live for the users to access */
cdev_add(&dummy_cdev, devt, 1);

dummy_device = device_create(dummy_class,
                            NULL,   /* no parent device */
                            devt,    /* associated dev_t */
                            NULL,   /* no additional data */
                            "dummy_char");  /* device name */
Run Code Online (Sandbox Code Playgroud)

cdev_add 和 device_create 在这段代码中做了什么?

dha*_*hka 5

要使用字符驱动程序,首先应该在系统中注册它。然后你应该将它暴露给用户空间。

cdev_initcdev_add函数执行字符设备注册。 cdev_add将字符设备添加到系统中。当cdev_add函数成功完成时,设备处于活动状态,内核可以调用其操作。

为了从用户空间访问这个设备,你应该在/dev. 为此,您可以使用class_create创建虚拟设备类,然后sysfs使用device_create函数创建设备并注册它。device_create将在/dev.

Linux设备驱动程序,第三版,对过程的一个很好的说明第3章(字符驱动程序)(class_create并且device_create不包括在这本书)。