device_create()
时间: 2023-09-04 18:15:53 浏览: 51
`device_create()` 函数是用于创建一个新的设备节点的,它接收一个指向 `struct class` 结构体的指针、父设备节点、设备号以及设备名称作为参数。成功创建一个设备节点后,函数返回一个指向 `struct device` 的指针,否则返回一个错误码。
以下是一个示例代码片段,展示了如何使用 `device_create()` 函数创建一个设备节点:
```c
#include <linux/device.h>
static struct class *my_class;
static struct device *my_device;
static int __init my_module_init(void)
{
my_class = class_create(THIS_MODULE, "my_class_name");
if (IS_ERR(my_class)) {
printk(KERN_ERR "Failed to create class\n");
return PTR_ERR(my_class);
}
my_device = device_create(my_class, NULL, MKDEV(0, 0), NULL, "my_device_name");
if (IS_ERR(my_device)) {
class_destroy(my_class);
printk(KERN_ERR "Failed to create device\n");
return PTR_ERR(my_device);
}
return 0;
}
static void __exit my_module_exit(void)
{
device_destroy(my_class, MKDEV(0, 0));
class_destroy(my_class);
}
module_init(my_module_init);
module_exit(my_module_exit);
```
在这个例子中,我们创建了一个名为 "my_device_name" 的设备节点,并将其添加到名为 "my_class_name" 的设备类中。注意,我们使用了 `MKDEV()` 宏来创建设备号,这里使用的是 0 号主设备和 0 号次设备。在模块退出函数中,我们删除了该设备节点并销毁了设备类。
需要注意的是,在使用 `device_create()` 创建设备节点时,如果没有指定父设备节点,可以传入 `NULL`。父设备节点通常用于表示设备之间的层次关系,例如一个传感器设备可能有一个父设备节点表示该传感器所连接的控制器。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)