首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么设备注册不创建设备文件?

问为什么设备注册不创建设备文件?
EN

Unix & Linux用户
提问于 2022-04-12 02:07:26
回答 1查看 624关注 0票数 1

目前,我正在学习Linux设备驱动程序,我觉得自己对设备如何在Linux中实例化产生了根本性的误解。

在Linux模块中,我可以调用alloc_chrdev_region()向内核注册设备。具体来说,这个函数是

代码语言:javascript
复制
int alloc_chrdev_region(dev_t *dev, unsigned int firstminor,
 unsigned int count, char *name);

它生成设备编号(主要/次要)并接受设备名称。

成功执行后,将在/proc/devices中创建一个主要编号和设备类型名称的条目。但是,/dev中没有生成任何设备文件。相反,我必须发出一个mknod调用来生成设备文件。

所以我的问题是:为什么?

这似乎没有必要,因为我已经指定了要在内核中注册的设备类型、名称和数量。为什么没有自动创建设备文件?

EN

回答 1

Unix & Linux用户

发布于 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()的用法。

这也是一个简单的例子。请注意,这不是一个完整的代码。

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Unix & Linux提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://unix.stackexchange.com/questions/698802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档