#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/sysfs.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);
return count;
}
static struct kobj_attribute foo_attribute = _ATTR(foo, 0666, foo_show, foo_store);
static struct attribute *attrs[] = {
&foo_attribute.attr,
NULL,
};
static struct attribute_group attr_group = {
.attrs = attrs,
};
static struct kobject *example_kobj;
static int __init example_init(void)
{
int retval;
example_kobj = kobject_create_and_add("kobject_example",kernel_kobj); ①
if (!example_kobj)
return -ENOMEM;
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("Greg Kroah-Hartman greg@kroah.com");
注释:
①这里新创建并添加了一个struct kobject对象。在实际的程序中,可能需要挂载到指定的kobjcet对象下(如某些platform驱动),那时就不需要自己再创建kobject对象了。
②如果不需要自己创建kobjcet对象,那么可以调用sysfs_remove_group()来删除。sysfs_remove_group()与sysfs_create_group()具有相同的参数类型。
另外,更多的程序请参照kernel/samples/kobject/kobject-example.c.