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

来源:互联网 发布:linux杀java进程 编辑:程序博客网 时间:2024/06/08 04:29

看到内核中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
原创粉丝点击