在内核代码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时会显示加一后的结果。