自动创建设备节点是Linux设备驱动开发中的一个重要环节,它允许设备驱动程序在内核中注册后,自动在/dev
目录下创建对应的设备文件,从而使得用户空间程序可以通过标准的文件操作接口(如open、read、write等)与硬件设备进行交互。 ❤
一、自动创建设备节点的概念
在Linux中,一切皆文件,设备驱动程序也不例外。设备驱动程序通过设备文件的形式向上层程序提供接口。设备文件通常位于/dev
目录下,包括字符设备文件、块设备文件、网络设备文件等。这些特殊类型的文件使用统一的文件操作函数(如open、read、write等)进行访问。
二、相关函数和宏定义
(1)class_create
宏定义
#define class_create(owner, name) \
({ \
static struct lock_class_key __key; \
__class_create(owner, name, &__key); \
})
实际上,class_create
是一个宏定义,它内部调用了__class_create
函数。
参数:
owner
:指向模块所有者的指针,通常为THIS_MODULE
宏,表示当前模块。name
:设备类的名称,该名称将用于在/sys/class/
目录下创建对应的目录。
返回值:返回指向新创建的struct class
结构体的指针,如果创建失败则返回ERR_PTR
错误码。
(2)class_destroy
/**
* class_destroy - destroys a struct class structure
* @cls: pointer to the struct class that is to be destroyed
*
* Note, the pointer to be destroyed must have been created with a call
* to class_create().
*/
void class_destroy(struct class *cls)
{
if ((cls == NULL) || (IS_ERR(cls)))
return;
class_unregister(cls);
}
功能:class_destroy
函数用于销毁之前通过class_create
创建的设备类。它会删除/sys/cla