linux内核源码分析之sysfs文件系统(二)

目录

一、实现功能

二、源码

三、模块解析 

1、函数kobject_create_and_add

2、kobj属性,方法

3、函数sysfs_create_group

4、函数kobject_put


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);


参考:

 内核源码

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为了维护世界和平_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值