如何从Linux内核模块的init_module代码创建设备节点? [英] How to create a device node from the init_module code of a Linux kernel module?
问题描述
我正在为linux内核编写一个模块,我想在init函数中创建一些设备节点
I am writing a module for the linux kernel and I want to create some device nodes in the init function
int init_module(void)
{
Major = register_chrdev(0, DEVICE_NAME, &fops);
// Now I want to create device nodes with the returned major number
}
我还希望内核为我的第一个节点分配一个次要编号,然后由我自己分配其他节点的次要编号.
I also want the kernel to assign a minor number for my first node, and then I will assign the other nodes' minor numbers by myself.
如何在代码中执行此操作.我不想使用mknod从外壳创建设备
How can I do this in the code. I dont want to create devices from the shell using mknod
推荐答案
要对设备编号和设备创建有更多控制,您可以执行以下步骤(而不是register_chrdev()
):
To have more control over the device numbers and the device creation you could do the following steps (instead of register_chrdev()
):
- 致电
alloc_chrdev_region()
获取一个主要号码和一系列次要号码. - 使用
class_create()
为您的设备创建设备类. - 对于每个设备,调用
cdev_init()
和cdev_add()
将字符设备添加到系统中. - 对于每个设备,呼叫
device_create()
.结果,除其他外, Udev 将为您的设备创建设备节点.不需要mknod
等.device_create()
还允许您控制设备的名称.
- Call
alloc_chrdev_region()
to get a major number and a range of minor numbers to work with. - Create device class for your devices with
class_create()
. - For each device, call
cdev_init()
andcdev_add()
to add the character device to the system. - For each device, call
device_create()
. As a result, among other things, Udev will create device nodes for your devices. No need formknod
or the like.device_create()
also allows you to control the names of the devices.
网上可能有很多这样的例子,其中一个在这里.
There are probably many examples of this on the Net, one of them is here.
这篇关于如何从Linux内核模块的init_module代码创建设备节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!