今天无意中在内核里看到了这段源码,才忽然间对内核文件系统里文件节点及其属性的创建有了清晰的了解,结合代码分析一番,以备日后之需。
内核源码路径:/kernel/samples/kobject/ ,目录下有三个文件:kobject-example.c 和 kset-example.c 以及一个Makefile.
首先,kobject和kset的区别:
kobject建立的目录下只能添加文件;
kset建立的目录下既可以添加文件,还可以添加目录,它是一类kobject的集合。
struct kobject {
const char *name; //sysfs中的文件名
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的创建及相关:
int kobject_set_name(struct kobject *kobj, const char *name, ...)
__attribute__((format(printf, 2, 3)));
kobject_set_name_vargs(struct kobject *kobj, const char *fmt,
va_list vargs);
void kobject_init(struct kobject *kobj, struct kobj_type *ktype);
int __must_check kobject_add(struct kobject *kobj,
struct kobject *parent,
const char *fmt, ...)
__attribute__((format(printf, 3, 4)));
int __must_check kobject_init_and_add(struct kobject *kobj,
struct kobj_type *ktype,
struct kobject *parent,
const char *fmt, ...)
__attribute__((format(printf, 4, 5)));
void kobject_del(struct kobject *kobj);
struct kobject * __must_check kobject_create(void);
struct kobject * __must_check kobject_create_and_add(const char *name,
struct kobject *parent);
int __must_check kobject_rename(struct kobject *, const char *new_name);
int __must_check kobject_move(struct kobject *, struct kobject *);
struct kobject *kobject_get(struct kobject *kobj);
char *kobject_get_path(struct kobject *kobj, gfp_t flag);
struct kobj_attribute {
struct attribute attr;
ssize_t (*show)(struct kobject *kobj, struct kobj_attribute *attr,
char *buf);
ssize_t (*store)(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count);
};
kobject-example.c
module_init(example_init); -> example_init();
调用example_kobj = kobject_create_and_add("kobject_example", kernel_kobj);
//kernel_kobj 为目录:/sys/kernel/
module_exit(example_exit); 调用kobject_put(example_kobj);减少引用计数