#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/sysfs.h>
#include <linux/kobject.h>
#include <linux/slab.h>
#include <linux/fs.h>
MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION("for linux driver learn");
int a = 10;
module_param(a, int, S_IRUGO);
struct kobject *rifle_kobj = NULL;
/*
struct kobj_type {
void (*release)(struct kobject *);
struct sysfs_ops *sysfs_ops;
struct attribute **default_attrs;
};
struct attribute {
char *name;
struct module *owner;
mode_t mode;
};
struct sysfs_ops {
ssize_t (*show)(struct kobject *kobj, struct attribute *attr, char *buffer);
ssize_t (*store)(struct kobject *kobj, struct attribute *attr, const char *buffer, size_t size);
};
*/
// 要创建的属性设备文件[文件名 + 权限]
struct attribute rifle_attrs[] = {
[0] = {"AssaultRifle",S_IRUGO |S_IWUSR},
[1] = {"SniperRifle",S_IRUGO |S_IWUSR},
{NULL}
};
void rifle_release(struct kobject * k)
{
kfree(k);
}
// 属性文件初值
char AssaultRifle[100] = {"ak47"};
char SniperRifle[100] = {"as50"};
// 给应用层的属性获取接口
ssize_t rifle_show(struct kobject *kobj, struct attribute *attr, char *buffer)
{
if(0 == strcmp(attr->name, "AssaultRifle"))
memcpy(buffer, AssaultRifle, 100);
else
if(0 == strcmp(attr->name, "SniperRifle"))
memcpy(buffer, SniperRifle, 100);
return 100;
}
// 响应应用层属性更改接口
ssize_t rifle_store(struct kobject *kobj, struct attribute *attr, const char *buffer, size_t size)
{
if(0 == strcmp(attr->name, "AssaultRifle"))
memcpy(AssaultRifle, buffer, size);
else
memcpy(SniperRifle, buffer, size);
return size;
}
// 属性文件操作方法
struct sysfs_ops rifle_ops = {
.show = rifle_show,
.store = rifle_store
};
struct kobj_type rifle_type = {
.release = rifle_release,
.sysfs_ops = &rifle_ops,
};
static int rifleattr_init(void)
{
printk("module install: a = %d\n", a);
rifle_kobj = kzalloc(sizeof(struct kobject), GFP_KERNEL);
kobject_init(rifle_kobj, &rifle_type);
kobject_add(rifle_kobj, NULL, "rifle");
sysfs_create_file(rifle_kobj, &rifle_attrs[0]);
sysfs_create_file(rifle_kobj, &rifle_attrs[1]);
return 0;
}
static void rifleattr_exit(void)
{
printk("module release\n");
sysfs_remove_file(rifle_kobj, &rifle_attrs[0]);
sysfs_remove_file(rifle_kobj, &rifle_attrs[1]);
kobject_del(rifle_kobj);
}
module_init(rifleattr_init);
module_exit(rifleattr_exit);
sysfs属性旋钮文件实例
最新推荐文章于 2023-05-13 18:24:53 发布