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_status,
0444,
scanner_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)