我是 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 */
这段代码中的 cdev_add 和 device_create 做了什么?
最佳答案
要使用字符驱动程序,首先你应该在系统中注册它。然后你应该把它暴露给用户空间。
cdev_init
和cdev_add
函数执行字符设备注册。
cdev_add将字符设备添加到系统中。当 cdev_add
函数成功完成时,设备处于事件状态并且内核可以调用其操作。
为了从用户空间访问这个设备,你应该在/dev
中创建一个设备节点。您可以通过使用 class_create 创建一个虚拟设备类来做到这一点, 然后创建一个设备并使用 device_create 向 sysfs
注册它功能。 device_create
将在 /dev
中创建一个设备文件。
阅读Linux Device Drivers, Third Edition , 第 3 章(字符驱动程序)很好地描述了该过程(class_create
和 device_create
未包含在本书中)。
关于linux - cdev_add 和 device_create 函数之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50377327/