Linux v2.6内核编程之/sys/中的kobject

在内核代码kernel/samples/kobject路径下有两个样例文件,一个是文件演示,一个是文件夹演示。
注意samples文件夹同级的Makefile内要打开。
kobject里的Makefile也要打开。

编译成功,insmod后,前者会在/sys/kernel/kobject_example文件夹下建立三个文件,演示读写功能;后者会在/sys/kernel/kset_example路径下建立三个文件夹,并且三个文件夹内分别再有三个文件,来演示文件夹进入功能和文件读写功能。

看到内核中Greg Kroah-Hartman的关于object的样例,再精简一下,用来演示怎样在sys文件系统中建立文件夹与文件结点,为自己的驱动添加一种用户接口。
源文件mykobject.c

/*
 * Sample kobject implementation
 * Released under the GPL version 2 only.
 */
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/module.h>
#include <linux/init.h>

static int foo;

static ssize_t foo_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
	return sprintf(buf, "%d\n", foo);
}

static ssize_t foo_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count)
{
	sscanf(buf, "%du", &foo);
	foo += 1;
	return count;
}

static struct kobj_attribute foo_attribute =
	__ATTR(foo, 0666, foo_show, foo_store);

static struct attribute *attrs[] = {
	&foo_attribute.attr,
	NULL,	/* need to NULL terminate the list of attributes */
};

static struct attribute_group attr_group = {
	.attrs = attrs,
};

static struct kobject *example_kobj;
static int __init example_init(void)
{
	int retval;

	/*
	 * Create a simple kobject with the name of "csdn", located under /sys/
	 */
	example_kobj = kobject_create_and_add("csdn", NULL);
	if (!example_kobj)
		return -ENOMEM;

	/* Create the files associated with this kobject */
	retval = sysfs_create_group(example_kobj, &attr_group);
	if (retval)
		kobject_put(example_kobj);

	return retval;
}

static void __exit example_exit(void)
{
	kobject_put(example_kobj);
}

module_init(example_init);
module_exit(example_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("csdn.net/yilonglucky");

这样,我们在/sys/下建立了一个文件夹叫做csdn,其中包含一个文件结点叫做foo。
可以向其echo数字,cat时会显示加一后的结果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yilonglucky

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

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

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

打赏作者

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

抵扣说明:

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

余额充值