1. 程式人生 > >裝置驅動模型之:kobject,kset,ktype(三)

裝置驅動模型之:kobject,kset,ktype(三)

這篇部落格裡面對於kobject作用做了一個剖析,這篇部落格是對於kobject一個實際運用,程式碼如下:
<kobject.c>


#include <linux/init.h>
#include <linux/module.h>
#include <linux/kobject.h>
#include <linux/sysfs.h>

static struct kobject kobj;

static void kobj_release(struct kobject *kobj)
{
        printk("will release : %s\n"
, kobj->name); } static ssize_t kobj_show(struct kobject * kobj, struct attribute * attr,char * buff) { int ret = 0; printk("this is in kboj_show , and attr: %s\n", attr->name); return ret; } static ssize_t kobj_store(struct kobject *kobj,struct attribute *attr,const char
*buff, size_t count) { int ret = 0; printk("this is in kboj_store , and attr: %s\n", attr->name); return ret; } static struct sysfs_ops k_sysfs_ops = { .show = kobj_show, .store = kobj_store }; static struct attribute test_attr1 = { .name = "alex1"
, .mode = S_IRWXUGO }; static struct attribute test_attr2 = { .name = "alex2", .mode = S_IRWXUGO }; static struct attribute * kobj_def_attrs[] = { & test_attr1, & test_attr2, NULL }; static struct kobj_type k_type = { .release = kobj_release, .sysfs_ops = &k_sysfs_ops, .default_attrs = kobj_def_attrs }; static inline int __init kobject_test_init(void) { int ret = 0; memset(&kobj, 0, sizeof(kobj)); kobject_set_name(&kobj, "alex"); ret = kobject_init_and_add(&kobj, & k_type , NULL, "alex"); return ret; } static inline void __exit kobject_test_exit(void) { kobject_del(&kobj); kobject_put(&kobj); } module_init(kobject_test_init); module_exit(kobject_test_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Alexander");

實際執行結果如下:

[email protected]:/usr/src/linux-2.6.39/driver/kobject# ls /sys/alex/
alex1  alex2
[email protected]:/usr/src/linux-2.6.39/driver/kobject# cat /sys/alex/alex1 
[email protected]:/usr/src/linux-2.6.39/driver/kobject# dmesg
[21000.571516] this is in kboj_show , and attr: alex1
[email protected]:/usr/src/linux-2.6.39/driver/kobject# cat /sys/alex/alex2 
[email protected]:/usr/src/linux-2.6.39/driver/kobject# dmesg
[21000.571516] this is in kboj_show , and attr: alex1
[21007.857229] this is in kboj_show , and attr: alex2
[email protected]:/usr/src/linux-2.6.39/driver/kobject# rmmod kobject.ko 
[email protected]:/usr/src/linux-2.6.39/driver/kobject# dmesg
[21000.571516] this is in kboj_show , and attr: alex1
[21007.857229] this is in kboj_show , and attr: alex2
[21021.994598] will release : alex
[email protected]:/usr/src/linux-2.6.39/driver/kobject#