在内核中创建文件或目录需要通过sysfs接口来完成。以下是一个示例内核模块,可以在/sys/class/目录下创建lan文件,如果lan目录已经存在,则在其中创建test文件:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sysfs.h>

static struct kobject *lan_kobj;

static ssize_t lan_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
    return sprintf(buf, "lan\n");
}

static struct kobj_attribute lan_attribute = __ATTR(lan, 0444, lan_show, NULL);

static ssize_t test_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
    return sprintf(buf, "test\n");
}

static struct kobj_attribute test_attribute = __ATTR(test, 0444, test_show, NULL);

static int __init sysfs_example_init(void)
{
    int result;

    lan_kobj = kobject_create_and_add("lan", kernel_kobj); // 创建lan目录

    if (!lan_kobj) {
        pr_err("Failed to create lan directory\n");
        return -ENOMEM;
    }

    result = sysfs_create_file(lan_kobj, &lan_attribute.attr); // 在lan目录下创建lan文件

    if (result) {
        pr_err("Failed to create lan file\n");
        kobject_put(lan_kobj);
        return result;
    }

    result = sysfs_create_file(lan_kobj, &test_attribute.attr); // 在lan目录下创建test文件

    if (result) {
        pr_err("Failed to create test file\n");
        sysfs_remove_file(lan_kobj, &lan_attribute.attr);
        kobject_put(lan_kobj);
        return result;
    }

    return 0;
}

static void __exit sysfs_example_exit(void)
{
    sysfs_remove_file(lan_kobj, &lan_attribute.attr);
    sysfs_remove_file(lan_kobj, &test_attribute.attr);
    kobject_put(lan_kobj);
}

module_init(sysfs_example_init);
module_exit(sysfs_example_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Sysfs Example Module");

将以上代码保存为sysfs_example.c,然后使用以下命令编译并加载内核模块:

make -C /lib/modules/$(uname -r)/build M=$(pwd) modules
sudo insmod sysfs_example.ko

加载内核模块后,可以在/sys/class/目录下看到lan目录和其中的lan、test文件。可以通过cat命令查看文件内容:

cat /sys/class/lan/lan
cat /sys/class/lan/test

请注意,这只是一个示例,实际应用中可能需要根据需求进行修改和扩展


原文地址: https://www.cveoy.top/t/topic/ieQQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录