linux设备模型之内核对象kobject

linux中一切皆文件
1.内核对象kobject

struct kobject {
    const char      *name; //对象的名字
    struct list_head    entry;
    struct kobject      *parent;//对象的上层
    struct kset     *kset; //当前对象属于的kset指针 
    struct kobj_type    *ktype;//文件操作集
    struct sysfs_dirent *sd;
    struct kref     kref;
    unsigned int state_initialized:1;
    unsigned int state_in_sysfs:1;
    unsigned int state_add_uevent_sent:1;
    unsigned int state_remove_uevent_sent:1;
    unsigned int uevent_suppress:1;
};
相关操作函数:
//初始化一个kobject
void kobject_init(struct kobject *kobj, struct kobj_type *ktype)
//添加一个kobject
int
kobject_add(struct kobject *kobj, struct kobject *parent,const char *fmt, ...)
     kobject_add_varg(kobj, parent, fmt, args);
        kobject_set_name_vargs(kobj, fmt, vargs);
        kobject_add_internal(struct kobject *kobj)
            if (kobj->kset) {
                if (!parent)
                        parent = kobject_get(&kobj->kset->kobj);
                kobj_kset_join(kobj);
                kobj->parent = parent;
            }
        error = create_dir(kobj);//创建目录
            error = sysfs_create_dir(kobj);
            create_diif (kobj->parent)
                parent_sd = kobj->parent->sd;
            else
                parent_sd = &sysfs_root;
                create_dir(kobj, parent_sd, type, ns, kobject_name(kobj), &sd);
//初始化与添加
int kobject_init_and_add(struct kobject *kobj, struct kobj_type *ktype,struct kobject *parent, const char *fmt, ...)
//创建并添加
struct kobject *kobject_create_and_add(const char *name, struct kobject *parent)
        kobj = kobject_create();
            kobject_init(kobj, &dynamic_kobj_ktype);
        retval = kobject_add(kobj, parent, "%s", name);
extern void kobject_del(struct kobject *kobj);

例子:
#include <linux/module.h>
#include <linux/kobject.h>

static struct kobject * parent = NULL;
static struct kobject * child = NULL;

static int __init kobject_test_init(void)
{
    printk(KERN_INFO "%s\n",__FUNCTION__);
    parent = kobject_create_and_add("father_obj",NULL);
    child = kobject_create_and_add("child_obj",parent);
    return 0;
}
static void __exit kobject_test_exit(void)
{
    printk(KERN_INFO "%s\n",__FUNCTION__);
    kobject_del(child);
    kobject_del(parent);
}

module_init(kobject_test_init); 
module_exit(kobject_test_exit);

MODULE_AUTHOR("derrick email: [email protected]");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Kobject test Module");
MODULE_ALIAS("Kobject test Module");
//在sys目录下有:
//sys/father_obj/child_obj目录

你可能感兴趣的:(linux,内核)