设备模型五(实例代码)

    xiaoxiao2021-03-25  105

    前言 这篇主要是对前四章的总结 本例子参考<<深入linux设备驱动内核机制>> 例子真好, 我在此之上又添加了一些 #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/kobject.h> #include <linux/sysfs.h> #include <linux/slab.h> static struct kobject * parent; static struct kobject * child; static struct kset *c_kset; static unsigned long flag = 1; static unsigned long xx = 1; static ssize_t att_show(struct kobject *kobj, struct attribute *attr, char *buf) { size_t count = 0; count += sprintf(&buf[count], "%lu\n", flag); return count; } static ssize_t att_store(struct kobject *kobj, struct attribute *attr, const char* buf, size_t count) { flag = buf[0] - '0'; switch(flag) { case 0: printk(KERN_ALERT "ADD===============\n"); //消息发不出去 kobj->uevent_suppress = 1; kobject_uevent(kobj, KOBJ_ADD); break; case 1: printk(KERN_ALERT "REMOVE===============\n"); //消息可以发出去 kobj->uevent_suppress = 0; kobject_uevent(kobj, KOBJ_REMOVE); break; case 2: printk(KERN_ALERT "CHANGE===============\n"); xx = 1; kobject_uevent(kobj, KOBJ_CHANGE); break; case 3: xx = 0; printk(KERN_ALERT "MOVE===============\n"); kobject_uevent(kobj, KOBJ_MOVE); break; case 4: printk(KERN_ALERT "ONLINE===============\n"); kobject_uevent(kobj, KOBJ_ONLINE); break; case 5: printk(KERN_ALERT "OFFLINE===============\n"); kobject_uevent(kobj, KOBJ_OFFLINE); break; } return count; } static struct attribute cld_att={ .name = "cldatt", .mode = S_IRUGO | S_IWUSR, }; static const struct sysfs_ops att_ops={ .show = att_show, .store = att_store, }; static struct kobj_type cld_ktype={ .sysfs_ops = &att_ops, }; static int ma_ok_uevent(struct kset *kset, struct kobject *kobj, struct kobj_uevent_env *env) { add_uevent_var(env, "autor_name=%s", "mxg......"); add_uevent_var(env, "shi[%s]", "dashen"); return 0; } static int uevent_filter(struct kset *kset, struct kobject *kobj) { struct kobj_type *ktype = get_ktype(kobj); //过滤机制,kobject_uevent发送消息调用c_kset的.filter确定是不是cld_obj发的 //通过ktype的对比,比如前一篇的说明中,如果有xx其kset也是c_kset, xx的kobj调用kobject_uevent,调用c_kset的.filter判断不是xx的ktype类型, if (ktype == &cld_ktype) return xx; return 0; } static const struct kset_uevent_ops ma_uevent = { .uevent = ma_ok_uevent, .filter = uevent_filter, }; static int kobj_demo_init(void) { int err; parent = kobject_create_and_add("pa_obj", NULL); child = kzalloc(sizeof(*child), GFP_KERNEL); if(!child) return -1; c_kset = kset_create_and_add("c_kset", &ma_uevent, parent); if(!c_kset) return -1; child->kset=c_kset; err = kobject_init_and_add(child, &cld_ktype, parent, "cld_obj"); if(err) return err; err = sysfs_create_file(child, &cld_att); return err; } static void kobj_demo_exit(void) { sysfs_remove_file(child, &cld_att); kset_unregister(c_kset); kobject_del(child); kobject_del(parent); } MODULE_LICENSE("GPL"); module_init(kobj_demo_init); module_exit(kobj_demo_exit);

    代码所对应的关系如下图

    转载请注明原文地址: https://ju.6miu.com/read-12935.html

    最新回复(0)