在device driver中给device快速添加属性文件

1. 头文件 #include <linux/device.h>

2. 定义属性文件的show, store函数

static ssize_t scanner_status_show(
    struct device *dev,
    struct device_attribute *attr,
    char *buf)
{
    int status = 0;
    unsigned int gpio;
    gpio = info.pin[1].gpio.gpio;
    status = __gpio_get_value(gpio);
    if(status == 0){
        status = 1;
    }else{
        status = 0;
    }
    return sprintf(buf, "%d\n", status);
}
这里只定义了一个show函数(因为这次改动只需要定义show)

3. 用DEVICE_ATTR (这个过程后续具体分析)
static DEVICE_ATTR( scanner_status0444scanner_status_show, NULL);

其中: 
scanner_status:          属性文件名
0444:                             读写权限,比如当前是对任何权限的用户都只有读权限
scanner_status_show:  在应用层读该文件时,最终会调用到该函数
NULL:                            当前没有定义,所以填NULL; 实际上这个地方可以填store函数,即应用层write该文件时最终调用到该函数

show/store函数都不是必须的,根据功能需要来实现。


4.在probe(或module_init)中,创建设备属性文件

   ret = device_create_file(gpio_g870s_cdev, & dev_attr_scanner_status);
   if (ret != 0) {
       printk("Failed to create scanner_status sysfs files: %d\n", ret);
       //return ret;
  }
  
device_create_file函数原型(drivers/base/core.c):
    int device_create_file(struct device *dev,  const struct device_attribute *attr)
第一个参数:    是struct device 类型的指针,然属性文件跟具体各设备挂上钩(static    struct device * gpio_g870s_cdev)
第二个参数:    跟之前定义的属性挂上钩, dev_attr_scanner_status,其实就是  dev_atrr_+属性文件名

5.有创建就有销毁,驱动模块卸载时,要在remove(或module_exit)中,销毁属性文件

     device_remove_file(gpio_g870s_cdev, & dev_attr_scanner_status);

函数原型同样在drivers/base/core.c中,参数也是一样的:
void device_remove_file(struct device *dev,  const struct device_attribute *attr)



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值