Linux底层驱动如何创建节点文件

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

device_create_file
class_create_file
driver_create_file

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

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

2、那怎么去实现呢?

      我们以class为例。

我们一般是先创建class再创建device。首先先创建类:

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 scan_ext_with[] = {
    __ATTR(scan_ext, 0664, NULL, scan_ext_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 scan_ext_with[] = {
    __ATTR(scan_ext, 0664, NULL, scan_ext_with),
    __ATTR_NULL,
};
    注意是device_attribute不是class_attribute!!!!!!,这里要特别留意下,否则可能掉坑里!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值