2021-07-22 06:35:24 +08:00
|
|
|
/*
|
2024-09-03 14:48:19 +08:00
|
|
|
* hello-sysfs.c sysfs 示例
|
2021-07-22 06:35:24 +08:00
|
|
|
*/
|
|
|
|
#include <linux/fs.h>
|
2021-07-22 06:58:13 +08:00
|
|
|
#include <linux/init.h>
|
|
|
|
#include <linux/kobject.h>
|
|
|
|
#include <linux/module.h>
|
2021-07-22 06:35:24 +08:00
|
|
|
#include <linux/string.h>
|
2021-07-22 06:58:13 +08:00
|
|
|
#include <linux/sysfs.h>
|
2021-07-22 06:35:24 +08:00
|
|
|
|
|
|
|
static struct kobject *mymodule;
|
|
|
|
|
2024-09-03 14:48:19 +08:00
|
|
|
/* 你希望能够更改的变量 */
|
2021-07-22 06:35:24 +08:00
|
|
|
static int myvariable = 0;
|
|
|
|
|
|
|
|
static ssize_t myvariable_show(struct kobject *kobj,
|
2021-09-02 15:15:07 +08:00
|
|
|
struct kobj_attribute *attr, char *buf)
|
2021-07-22 06:35:24 +08:00
|
|
|
{
|
|
|
|
return sprintf(buf, "%d\n", myvariable);
|
|
|
|
}
|
|
|
|
|
|
|
|
static ssize_t myvariable_store(struct kobject *kobj,
|
2021-09-02 15:15:07 +08:00
|
|
|
struct kobj_attribute *attr, char *buf,
|
2021-07-22 06:58:13 +08:00
|
|
|
size_t count)
|
2021-07-22 06:35:24 +08:00
|
|
|
{
|
|
|
|
sscanf(buf, "%du", &myvariable);
|
|
|
|
return count;
|
|
|
|
}
|
|
|
|
|
|
|
|
static struct kobj_attribute myvariable_attribute =
|
2021-09-02 15:15:07 +08:00
|
|
|
__ATTR(myvariable, 0660, myvariable_show, (void *)myvariable_store);
|
2021-07-22 06:35:24 +08:00
|
|
|
|
2021-07-22 06:58:13 +08:00
|
|
|
static int __init mymodule_init(void)
|
2021-07-22 06:35:24 +08:00
|
|
|
{
|
|
|
|
int error = 0;
|
|
|
|
|
2024-09-03 14:48:19 +08:00
|
|
|
pr_info("我的模块: 初始化完成\n");
|
2021-07-22 06:35:24 +08:00
|
|
|
|
2024-09-03 14:48:19 +08:00
|
|
|
mymodule = kobject_create_and_add("我的模块", kernel_kobj);
|
2021-07-22 06:35:24 +08:00
|
|
|
if (!mymodule)
|
|
|
|
return -ENOMEM;
|
|
|
|
|
|
|
|
error = sysfs_create_file(mymodule, &myvariable_attribute.attr);
|
|
|
|
if (error) {
|
2024-09-03 14:48:19 +08:00
|
|
|
pr_info("在 /sys/kernel/我的模块 创建 myvariable 文件失败\n");
|
2021-07-22 06:35:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return error;
|
|
|
|
}
|
|
|
|
|
2021-07-22 06:58:13 +08:00
|
|
|
static void __exit mymodule_exit(void)
|
2021-07-22 06:35:24 +08:00
|
|
|
{
|
2024-09-03 14:48:19 +08:00
|
|
|
pr_info("我的模块: 退出成功\n");
|
2021-07-22 06:35:24 +08:00
|
|
|
kobject_put(mymodule);
|
|
|
|
}
|
|
|
|
|
|
|
|
module_init(mymodule_init);
|
|
|
|
module_exit(mymodule_exit);
|
2021-08-08 01:24:59 +08:00
|
|
|
|
|
|
|
MODULE_LICENSE("GPL");
|
2024-09-03 14:48:19 +08:00
|
|
|
|