这篇博客里面对于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");
实际运行结果如下:
root@ubuntu:/usr/src/linux-2.6.39/driver/kobject# ls /sys/alex/
alex1 alex2
root@ubuntu:/usr/src/linux-2.6.39/driver/kobject# cat /sys/alex/alex1
root@ubuntu:/usr/src/linux-2.6.39/driver/kobject# dmesg
[21000.571516] this is in kboj_show , and attr: alex1
root@ubuntu:/usr/src/linux-2.6.39/driver/kobject# cat /sys/alex/alex2
root@ubuntu:/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
root@ubuntu:/usr/src/linux-2.6.39/driver/kobject# rmmod kobject.ko
root@ubuntu:/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
root@ubuntu:/usr/src/linux-2.6.39/driver/kobject#