15_sysfsLinux内核模块
01_basicLinux内核模块_the kernel was built by-CSDN博客文章浏览阅读989次,点赞3次,收藏3次。环境ID=ubuntuMakefilemodules:clean:basic.creturn 0;运行效果。_the kernel was built byhttps://blog.csdn.net/m0_37132481/article/details/136157384
环境
root@auto:/media/sf_D_DRIVE/kmodule/15_sysfs# cat /etc/os-release
PRETTY_NAME="Ubuntu 24.04.1 LTS"
NAME="Ubuntu"
VERSION_ID="24.04"
VERSION="24.04.1 LTS (Noble Numbat)"
VERSION_CODENAME=noble
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=noble
LOGO=ubuntu-logo
mysysfs.c
root@auto:/media/sf_D_DRIVE/kmodule/15_sysfs# cat mysysfs.c #include <linux/module.h> #include <linux/kobject.h>// implement ref:kernel/ksysfs.c #define TAG "hello# "static struct kobject *hello_kobj;static ssize_t hello1_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) {return sprintf(buf, "%s\n", __func__); }static ssize_t hello1_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) {return count; }static struct kobj_attribute hello_attr1 = {.attr = {.name = "hello1",.mode = 0777},.show = hello1_show,.store = hello1_store };static struct attribute * hello_attrs[] = {&hello_attr1.attr,{}, };static const struct attribute_group hello_attr_group = {.attrs = hello_attrs, };static int mysysfs_init(void) {int error;printk(TAG "%s called\n", __func__);hello_kobj = kobject_create_and_add("hello", NULL);if (!hello_kobj) {error = -ENOMEM;goto exit;}error = sysfs_create_group(hello_kobj, &hello_attr_group);if (error)goto kset_exit;return 0; kset_exit:kobject_put(hello_kobj); exit:return error; }static void mysysfs_exit(void) {printk(TAG "%s called\n", __func__);sysfs_remove_group(hello_kobj, &hello_attr_group);kobject_put(hello_kobj); }module_init(mysysfs_init); module_exit(mysysfs_exit);MODULE_LICENSE("GPL");
效果