linux驱动创建节点文件(device和class方式)

概述

创建sys目录下的属性节点有三种方式

device_create_file
class_create_file
driver_create_file

我们常用的是第一个和第二个,这三者的主要区别在第一个参数上,device依赖于device节点,class依赖于class节点(class_create)

device_create_file 创建的属性节点在device设备节点对应的路径下,同理device也是

具体使用

class

我们一般是先创建class再创建device,所以以class创建设备节点为例

首先先创建类

class_create(owner, name)
  • owner:一般填写THIS_MODULE
  • name:class的名字,在sys/class/下的文件夹名称

再调用创建文件命令

class_create_file(struct class *class,
const struct class_attribute *attr)
  • class:我们创建返回的class结构体
  • attr: class_attribute结构体,也是我们下一步要填写的参数

class_attribute结构体如下:

struct class_attribute {
struct attribute attr;
ssize_t (*show)(struct class *class, struct class_attribute *attr,
char *buf);
ssize_t (*store)(struct class *class, struct class_attribute *attr,
const char *buf, size_t count);
};
  • show也就是我们通过cat读取时所执行的函数
  • store是通过echo命令所执行的函数
  • attr:attribute结构体,里面有两个参数name也就是文件的名称,mode,对接口文件权限的设置

上面store、show函数的具体实现是需要我们按上面的格式自己编写函数

我们一般不会通过完成上面结构体的方式进行初始化,我们一般通过一下方式

static struct class_attribute k60168_Tran_With[] = {
   __ATTR(trans_with, 0664, NULL, k60168_trans_with),
   __ATTR_NULL,
};

__ATTR填入的就是我们上面所说的class_attribute的所有变量。

__ATTR_NULL也是必须的,具体是啥原因我也忘了

device

device节点依赖于class,所以device的创建也需要填写一些class的参数。

首先也是先创建device

device_create(struct class *cls, struct device *parent,
     dev_t devt, void *drvdata,
     const char *fmt, ...);
  • parent:父节点,一般为NULL
  • devt:设备号
  • drvdata:设备可能会使用到的数据,一般为NULL,正点是这么说的
  • fmt:在dev目录下创建的子目录的名称

然后再调用创建函数

int device_create_file(struct device *device,
     const struct device_attribute *entry);

其结构和上面的class类似就不多说了

device_attribute的结构体如下:

struct device_attribute {
struct attributeattr;
ssize_t (*show)(struct device *dev, struct device_attribute *attr,
char *buf);
ssize_t (*store)(struct device *dev, struct device_attribute *attr,
 const char *buf, size_t count);
};

也是通过如下的方式进行填充

static struct device_attribute k60168_Tran_With[] = {
   __ATTR(trans_with, 0664, NULL, k60168_trans_with),
   __ATTR_NULL,
};

注意是device_attribute不是class_attribute!!!!!!,我自己踩过的坑

作者:小菜鸡的逆袭原文地址:https://www.cnblogs.com/liming111/p/17229959.html

%s 个评论

要回复文章请先登录注册