目前,我正在学习Linux设备驱动程序,我觉得自己对设备如何在Linux中实例化产生了根本性的误解。
在Linux模块中,我可以调用alloc_chrdev_region()向内核注册设备。具体来说,这个函数是
int alloc_chrdev_region(dev_t *dev, unsigned int firstminor,
unsigned int count, char *name);它生成设备编号(主要/次要)并接受设备名称。
成功执行后,将在/proc/devices中创建一个主要编号和设备类型名称的条目。但是,/dev中没有生成任何设备文件。相反,我必须发出一个mknod调用来生成设备文件。
所以我的问题是:为什么?
这似乎没有必要,因为我已经指定了要在内核中注册的设备类型、名称和数量。为什么没有自动创建设备文件?
发布于 2022-08-04 15:12:05
alloc_chrdev_region()不创建设备节点/文件。alloc_chrdev_region()请求内核一个字符、设备号的范围,并且内核动态地选择可用的主号,并与第一个次要号一起返回。
为了自动创建设备文件,您需要使用device_create()。要使用device_create(),我们需要使用class_create()创建一个设备类,因为设备节点通常与类相关联。
查看内核源代码树中的hid-roccat驱动程序,例如在同一驱动程序中使用alloc_chrdev_region()和device_create()的用法。
这也是一个简单的例子。请注意,这不是一个完整的代码。
#define DRIVER_NAME "mydriver"
#define DRIVER_CLASS "mydriverclass"
static struct cdev my_device;
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = driver_open,
.release = driver_close,
.read = driver_read,
.write = driver_write
};
static int __init ModuleInit(void) {
/* Allocate a device number */
alloc_chrdev_region(&my_device_nr, 0, 1, DRIVER_NAME)
/* Create device class */
my_class = class_create(THIS_MODULE, DRIVER_CLASS))
/* create device file */
device_create(my_class, NULL, my_device_nr, NULL, DRIVER_NAME)
/* Initialize device file */
cdev_init(&my_device, &fops);
/* Regisering device to kernel */
dev_add(&my_device, my_device_nr, 1)
return 0;
}https://unix.stackexchange.com/questions/698802
复制相似问题