内核模块在sysfs中导出文件

1. 定义导出文件变量

static int my_debug = 0;

2. 实现导出文件的读写函数

//写文件
static ssize_t my_debug_store(struct device *dev,
                struct device_attribute *attr, const char *buf,
                size_t count)
{
    kstrtoint(buf, 10, &my_debug);

    return count;
}

//读文件
static ssize_t my_debug_show(struct device *dev,
                struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%d\n", my_debug);
}

3. 定义导出文件的读写属性

static DEVICE_ATTR_RW(my_debug);

3. probe函数创建

static struct class *eci_class = NULL;
static int ecibus_probe(struct platform_device *pdev)
{
    ...

    //1. 在/sys/class下创建目录
    eci_class = class_create(THIS_MODULE, CLASS_NAME);
    if (IS_ERR(eci_class)) {
        dev_err(dev, "class_create error\n");
        goto _ERR_FREE;
    }
    //2. 创建设备节点
    struct device *child_node = device_create(eci_class, NULL, MKDEV(ecibus_major, ecibus_minor), NULL, DEVICE_NAME);
    if (IS_ERR(child_node)) {
        dev_err(dev, "device_create error\n");
        goto _ERR_FREE;
    }
    //3.导出sysfs文件
    device_create_file(child_node, &dev_attr_my_debug);

    ...
}

Related Posts