hello_world-2.0之sys文件系统kobj
1.helloworld.c的源码
#include<linux/init.h>
#include<linux/module.h>
#include<linux/kobject.h>
#include<linux/sysfs.h>
#include<linux/string.h>
static int hello_value;
static ssize_t hello_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%d\n",hello_value);
}
static ssize_t hello_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
sscanf(buf, "%du", &hello_value);
return count;
}
static struct kobj_attribute hello_value_attribute = __ATTR(hello_value,0666,hello_show,hello_store);
static struct kobject *helloworld_kobj;
static int __init helloworld_init(void)
{
int retval;
helloworld_kobj = kobject_create_and_add("helloworld",kernel_kobj);
if(!helloworld_kobj)
return -ENOMEM;
retval = sysfs_create_file(helloworld_kobj,&hello_value_attribute);
if(retval)
kobject_put(helloworld_kobj);
return retval;
}
static void __exit helloworld_exit(void)
{
kobject_put(helloworld_kobj);
}
module_init(helloworld_init);
module_exit(helloworld_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("doublenian.xie@gmail.com");
2.运行结果
root@thiz:/sys/kernel/helloworld# ls
hello_value
root@thiz:/sys/kernel/helloworld# echo 1 > hello_value
root@thiz:/sys/kernel/helloworld# cat hello_value
1
3.分析
3.1 对于kobj有三方面:
(1)。目录项(/sys/kernel/helloworld),这个通过函数 kobject_create_and_add("helloworld",kernel_kobj);,可以在/sys下建立一个一个helloworld的目录项
(2).属性文件(hello_value),建立一个属性文件函数: sysfs_create_file(helloworld_kobj,&hello_value_attribute);这个同时也是建立了文件与操作之间的联系和对应
(3).操作( hello_show和hello_store):在sys系统中对文件的操作有一个函数:一个是show,一个是store;这个和普通的文件操作read和write有点类似,是他们的精简版。对于
ssprint和sscanf是对copy_from_user和copy_to_user函数的封装,指的是写内容到文件中。
如果是一组属性则可以
static struct attribute *attrs[] = {
&foo_attribute.attr,
&baz_attribute.attr,
&bar_attribute.attr,
NULL, /* need to NULL terminate the list of attributes */
};
&foo_attribute.attr,
&baz_attribute.attr,
&bar_attribute.attr,
NULL, /* need to NULL terminate the list of attributes */
};
............................
static struct attribute_group attr_group = {
.attrs = attrs,
};
.attrs = attrs,
};