內核版本:2.6.36
一、kobject應用舉例
Linux設備模型最基本的組成元素是kobject,我們先來看一個kobject的應用例子,該程序在Ubuntu 10.10, 2.6.32-38-generic-pae內核上調試通過。
該模塊執行過程如下圖所示:
- 1#include <linux/device.h>
- 2#include <linux/module.h>
- 3#include <linux/kernel.h>
- 4#include <linux/init.h>
- 5#include <linux/string.h>
- 6#include <linux/sysfs.h>
- 7#include <linux/stat.h>
- 8
- 9MODULE_AUTHOR("haoyu");
- 10MODULE_LICENSE("Dual BSD/GPL");
- 11
- 12void kobject_release(struct kobject *kobject);
- 13ssize_t kobject_attr_show(struct kobject *kobject, struct attribute *attr,char *buf);
- 14ssize_t kobject_attr_store(struct kobject *kobject,struct attribute *attr,const char *buf, size_t count);
- 15
- 16struct attribute kobject_attr1 = {
- 17 .name = "kobject_attr1",
- 18 .mode = S_IRWXUGO,
- 19};
- 20
- 21struct attribute kobject_attr2 = {
- 22 .name = "kobject_attr2",
- 23 .mode = S_IRWXUGO,
- 24};
- 25
- 26static struct attribute *kobject_def_attrs[] = {
- 27 &kobject_attr1,
- 28 &kobject_attr2,
- 29 NULL,
- 30};
- 31
- 32
- 33struct sysfs_ops kobject_sysfs_ops =
- 34{
- 35 .show = kobject_attr_show,
- 36 .store = kobject_attr_store,
- 37};
- 38
- 39struct kobj_type ktype =
- 40{
- 41 .release = kobject_release,
- 42 .sysfs_ops = &kobject_sysfs_ops,
- 43 .default_attrs = kobject_def_attrs,
- 44};
- 45
- 46void kobject_release(struct kobject *kobject)
- 47{
- 48 printk("kobject release.\n");
- 49}
- 50
- 51ssize_t kobject_attr_show(struct kobject *kobject, struct attribute *attr,char *buf)
- 52{
- 53 printk("kobject attribute show.\n");
- 54 if(strcmp(attr->name, "kobject_attr1") == 0)
- 55 printk("kobject_attr1.\n");
- 56 else if(strcmp(attr->name, "kobject_attr2") == 0)
- 57 printk("kobject_attr2.\n");
- 58 else
- 59 printk("no this attribute.\n");
- 60
- 61 sprintf(buf,"%s\n",attr->name);
- 62 return strlen(attr->name) + 2;
- 63}
- 64
- 65ssize_t kobject_attr_store(struct kobject *kobject,struct attribute *attr,const char *buf, size_t count)
- 66{
- 67 printk("kobject attribute store.\n");
- 68 if(strcmp(attr->name, "kobject_attr1") == 0)
- 69 printk("kobject_attr1.\n");
- 70 else if(strcmp(attr->name, "kobject_attr2") == 0)
- 71 printk("kobject_attr2.\n");
- 72 else
- 73 printk("no this attribute.\n");
- 74
- 75 printk("buf = %s\n",buf);
- 76 return count;
- 77}
- 78
- 79struct kobject kobj;
- 80static int kobject_test_init(void)
- 81{
- 82 printk("kboject test init.\n");
- 83 kobject_init_and_add(&kobj,&ktype,NULL,"kobject_test");
- 84 return 0;
- 85}
- 86
- 87static void kobject_test_exit(void)
- 88{
- 89 printk("kobject test exit.\n");
- 90 kobject_del(&kobj);
- 91}
- 92
- 93module_init(kobject_test_init);
- 94module_exit(kobject_test_exit);