cdev_add和device_create函数之间的区别?

问题描述 投票:2回答:1

我是Linux设备驱动程序开发的新手。我无法理解cdev_add实际上做了什么。我查看了一些简单的char设备驱动程序代码,我看到,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 */

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

linux linux-kernel linux-device-driver
1个回答
2
投票

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

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

要从用户空间访问此设备,您应该在/dev中创建设备节点。您可以通过使用class_create创建虚拟设备类,然后使用sysfs函数创建设备并使用device_create注册它来完成此操作。 device_create将在/dev中创建一个设备文件。

阅读Linux Device Drivers, Third Edition,第3章(字符驱动程序)以获得对该过程的良好描述(书中未涉及class_createdevice_create)。

© www.soinside.com 2019 - 2024. All rights reserved.