如何从 Linux 内核模块的 init_module 代码创建设备节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5970595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a device node from the init_module code of a Linux kernel module?
提问by Alptugay
I am writing a module for the linux kernel and I want to create some device nodes in the init function
我正在为 linux 内核编写一个模块,我想在 init 函数中创建一些设备节点
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.
我也希望内核为我的第一个节点分配一个次要编号,然后我将自己分配其他节点的次要编号。
How can I do this in the code. I dont want to create devices from the shell using mknod
我怎样才能在代码中做到这一点。我不想使用 mknod 从 shell 创建设备
采纳答案by Eugene
To have more control over the device numbers and the device creation you could do the following steps (instead of register_chrdev()
):
要更好地控制设备编号和设备创建,您可以执行以下步骤(而不是register_chrdev()
):
- 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, Udevwill create device nodes for your devices. No need formknod
or the like.device_create()
also allows you to control the names of the devices.
- 致电
alloc_chrdev_region()
以获取要使用的主要号码和一系列次要号码。 - 使用 为您的设备创建设备类
class_create()
。 - 对于每个设备,调用
cdev_init()
并将cdev_add()
字符设备添加到系统中。 - 对于每个设备,调用
device_create()
. 因此,除其他外,Udev将为您的设备创建设备节点。不需要mknod
之类的。device_create()
还允许您控制设备的名称。
There are probably many examples of this on the Net, one of them is here.
网络上可能有很多这样的例子,其中之一是here。
回答by Edwin Jose
static int __init ofcd_init(void) /* Constructor */
{
printk(KERN_INFO "Welcome!");
if (alloc_chrdev_region(&first, 0, 1, "char_dev") < 0) //$cat /proc/devices
{
return -1;
}
if ((cl = class_create(THIS_MODULE, "chardrv")) == NULL) //$ls /sys/class
{
unregister_chrdev_region(first, 1);
return -1;
}
if (device_create(cl, NULL, first, NULL, "mynull") == NULL) //$ls /dev/
{
class_destroy(cl);
unregister_chrdev_region(first, 1);
return -1;
}
cdev_init(&c_dev, &fops);
if (cdev_add(&c_dev, first, 1) == -1)
{
device_destroy(cl, first);
class_destroy(cl);
unregister_chrdev_region(first, 1);
return -1;
}
return 0;
}