目录
sysfs官方实例
一、实现功能
在sys/fs文件夹下创建hello,并在此文件夹下创建world文件,通过cat /sys/fs/hello/world 查看内容输出hello world,理解sysfs节点创建实现。
二、源码
#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;
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,
};
static struct attribute *attrs[] = {
&world_attribute.attr,
NULL, /* need to NULL terminate the list of attributes */
};
static struct attribute_group attr_group = {
.attrs = attrs,
};
static struct kobject *hello_kobj;
static int hello_init(void)
{
int retval;
hello_kobj = kobject_create_and_add("hello", fs_kobj);
if (!hello_kobj)
return -ENOMEM;
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");
三、模块解析
1、函数kobject_create_and_add
This function will create a kobject and place it in sysfs in the location underneath the specified parent kobject
struct kobject *kobject_create_and_add(char *name, struct kobject *parent);
2、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);
};
在实现中
- 注册属性名 world
- 注册show 为show_world
- 注册store为 store_world
- sysfs_create_group的参数
3、函数sysfs_create_group
To create simple attributes associated with this kobject
int sysfs_create_group(struct kobject *kobj, struct attribute_group *grp);
4、函数kobject_put
manipulating a kobject's reference counts
void kobject_put(struct kobject *kobj);
参考: