从一个例子入手:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/sysfs.h>
#include <linux/string.h>
#include <linux/stat.h>
/**
每一个kobject都有一个release函数,当kobject的引用计数为0的时候,这个函数会自动被调用
*/
void lee_type_release(struct kobject * kobj)
{
printk("leesagacious has calling---\n");
}
ssize_t lee_type_sysfs_ops_show(struct kobject * kobj,struct attribute * attr,char * buf)
{
printk("attribute_name = %s \n",attr->name);
sprintf(buf,"%s\n",attr->name);
return strlen(attr->name) + 2;
}
ssize_t lee_type_sysfs_ops_store(struct kobject *kobj,struct attribute * attr,const char * buf,size_t count )
{
printk("%s \n",buf);
strcpy(attr->name,buf);
return count;
}
struct attribute leeone = {
.name = "leeone",
.mode = S_IRWXUGO,
};
struct attribute leetwo = {
.name = "leetwo",
.mode = S_IRWXUGO,
};
struct attribute * lee_attrs[] = {
&leeone,
&leetwo,
NULL,
};
struct sysfs_ops lee_type_sysfs_ops = {
.show = lee_type_sysfs_ops_show,
.store = lee_type_sysfs_ops_store,
};
static struct kobj_type lee_type = {
.release = lee_type_release,
.sysfs_ops = &lee_type_sysfs_ops,
.default_attrs = lee_attrs,
};
struct kobject mykobj;
static int __init lee_init(void)
{
kobject_init_and_add(&mykobj,&lee_type,NULL,"mykobj");
return 0;
}
static void __exit lee_exit(void)
{
/**
kobject_del(&mykobj)
{
if (!kobj)
{
return;
}
从sysfs中移除该kobject
sysfs_remove_dir(kobj);
设置该kobject不在sysfs中
kobj->state_in_sysfs = 0;
从kset维护的kobject链表 上删除
kobj_kset_leave(kobj);
减少kobject的引用计数
kobject_put(kobj->parent);
父kobject设置为null
kobj->parent = NULL
}
*/
kobject_del(&mykobj);
}
module_init(lee_init);
module_exit(lee_exit);
MODULE_LICENSE("GPL");