sysfs文件系统来创建属性文件 DEVICE_ATTR class_create

在Linux内核中,可以使用sysfs文件系统来创建属性文件,以便在用户空间和内核空间之间传递信息。以下是一个使用sysfs_create_file函数创建属性文件的例程代码:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>

static ssize_t my_show_function(struct device *dev, struct device_attribute *attr, char *buf)
{
    /* 在这里编写读取属性文件的代码 */
}

static ssize_t my_store_function(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
    /* 在这里编写写入属性文件的代码 */
}

static DEVICE_ATTR(my_file_name, 0666, my_show_function, my_store_function);

static int __init my_init(void)
{
    struct class *my_class;
    struct device *my_device;
    int ret;

    my_class = class_create(THIS_MODULE, "my_class"); // 创建设备类

    if(IS_ERR(my_class)) {
        printk(KERN_ERR "Failed to create class.\n");
        return PTR_ERR(my_class);
    }

    my_device = device_create(my_class, NULL, 0, NULL, "my_device"); // 创建设备

    if(IS_ERR(my_device)) {
        printk(KERN_ERR "Failed to create device.\n");
        ret = PTR_ERR(my_device);
        goto class_destroy;
    }

    ret = device_create_file(my_device, &dev_attr_my_file_name); // 创建属性文件

    if(ret) {
        printk(KERN_ERR "Failed to create attribute file.\n");
        goto device_destroy;
    }

    return 0;

device_destroy:
    device_destroy(my_class, my_device);
class_destroy:
    class_destroy(my_class);
    return ret;
}

static void __exit my_exit(void)
{
    struct class *my_class;
    struct device *my_device;

    my_class = class_find(THIS_MODULE, "my_class 查找设备类
    my_device = device_find(my_class, NULL, NULL, match_all); // 查找设备

    device_remove_file(my_device, &dev_attr_my_file_name); // 移除属性文件
    device_destroy(my_class, my_device); // 销毁设备
    class_destroy(my_class); // 销毁设备类
}

module_init(my_init);
module_exit(my_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("ChatGPT");
MODULE_DESCRIPTION("A simple sysfs example module.");

在上述示例中,我们首先定义了两个回调函数my_show_function和my_store_function,用于处理读取和写入属性文件时的操作。然后,我们使用DEVICE_ATTR宏定义了一个名为my_file_name的属性文件,并将其访问权限设置为0666。

接下来,在__init函数中,我们创建了一个名为my_class的设备类,并device_create函数创建了一个名为my_device的设备。然后,我们使用device_create_file函数将属性文件添加到my_device设备中。

在__exit函数中,我们使用device_remove_file、device_destroy和class_destroy函数依次删除属性文件、销毁设备并销毁设备类。

需要注意的是,以上示例代码仅供参考,具体实现方式可能因系统版本和硬件平台而异。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全职编程-叶秋然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值