linux内核源码分析之sysfs文件系统
Posted 为了维护世界和平_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux内核源码分析之sysfs文件系统相关的知识,希望对你有一定的参考价值。
sysfs官方实例
在sys/fs文件夹下创建hello,并在此文件夹下创建world文件,通过cat /sys/fs/hello/world 查看内容输出hello world
/*
* OS-exp4 Implementation
*
* Program a module to create a subdirectory in sys/fs called
* hello, and a file named world under this directory,
* whose content is "hello world".
*
* Copyright (C) 2019 Larry <https://github.com/Larry955/OS-exp.git>.
*
* Released under the GPL.
*
*/
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
static int world;
/*
* The "world" file whose content is "hello world"
*/
static ssize_t show_world(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
return sprintf(buf, "hello world\\n");
static ssize_t store_world(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
sscanf(buf, "%du", &world);
return count;
static struct kobj_attribute world_attribute =
.attr =
.name = "world",
.mode = S_IWUSR | S_IRUGO,
,
.show = show_world,
.store = store_world,
;
/*
* Create a group of attributes so that we can create and destory them all
* at once.
*/
static struct attribute *attrs[] =
&world_attribute.attr,
NULL, /* need to NULL terminate the list of attributes */
;
/*
* An unnamed attribute group will put all of the attributes directly in
* the kobject directory. If we specify a name, a subdirectory will be
* created for the attributes with the directory being the name of the
* attribute group.
*/
static struct attribute_group attr_group =
.attrs = attrs,
;
static struct kobject *hello_kobj;
static int hello_init(void)
int retval;
/*
* Create a simple kobject with the name of "hello",
* located under /sys/fs/
*/
hello_kobj = kobject_create_and_add("hello", fs_kobj);
if (!hello_kobj)
return -ENOMEM;
/* Create the files associated with this kobject */
retval = sysfs_create_group(hello_kobj, &attr_group);
if (retval)
kobject_put(hello_kobj);
return retval;
static void hello_exit(void)
kobject_del(hello_kobj);
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
模块解析
kobj属性,方法
struct kobj_attribute
struct attribute attr;
ssize_t (*show)(struct kobject *kobj, struct kobj_attribute *attr,
char *buf);
ssize_t (*store)(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count);
;
struct kobject *kobject_create_and_add(char *name, struct kobject *parent);
This function will create a kobject and place it in sysfs in the location underneath the specified parent kobject
int sysfs_create_group(struct kobject *kobj, struct attribute_group *grp);
To create simple attributes associated with this kobject
void kobject_put(struct kobject *kobj);
manipulating a kobject's reference counts
参考内核学习连接
Linux内核源码/内存调优/文件系统/进程管理/设备驱动/网络协议栈-学习视频教程-腾讯课堂
以上是关于linux内核源码分析之sysfs文件系统的主要内容,如果未能解决你的问题,请参考以下文章