1、 创建相应的kobj_attribute。本实验用到打开手电筒,关闭手电筒,打开闪关灯,关闭闪光灯。所以创建四个kobj_attribute。因为四个格式比较类似,只有功能函数实现功能不同,所以本文只以sysfs_torch为例进行说明。
static struct kobj_attribute sysfs_torch = __ATTR(torch,S_IRUGO,sysfs_torch,NULL)
<pre name="code" class="cpp">static struct kobj_attribute sysfs_off = __ATTR(off,S_IRUGO,sysfs_off,NULL)
kobj_attribute 定义
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);
};
其中 __ATTR是一个宏,定义如下:
#define __ATTR(_name, _mode, _show, _store) { \
.attr = {.name = __stringify(_name), .mode = _mode }, \
.show = _show, \
.store = _store, \
}
2、创建相对应的功能函数 sysfs_torch
static ssize_t sysfs_torch(struct kobject *kobj,struct kobj_attribute *attr, char *buf) {
<span style="white-space:pre"> </span>实现手电筒功能代码。
}
3、创建 struct attribute 结构体数组 和 struct attribute_group 对象。
static struct attribute *flash_sysfs[] = {
&sysfs_torch.attr,
&sysfs_off.attr,
&sysfs_flash.attr,
NULL,
}
static struct attribute_group flash_attr_group = {
.attrs = flash_sysfs,
}
4、编写init函数
init函数主要调用函数
sysfs_create_group(struct kobject *kobj,const struct attribute_group *grp);
传递进参数就可以实现使用sysfs控制闪光灯。
也可以自己创建一个struct kobject 赋值为空,并使用kobject_create_and_add(const char *name ,struct kobject *parent) 创建。把该返回值传递给sysfs_create_group
我实现的时候,直接在 platform_probe 中添加sysfs_create_group,根据此创建的命令,会保存在和你设备所在的devices目录下,如果不知道在那个目录下,可以使用命令
find ./ -name "你定义的名字" 进行查找。
5、exit函数
下面的代码从此处转载
http://blog.sina.com.cn/s/blog_6a16c0ae0101b93s.html //
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kobject.h>
static ssize_t sysfs_read(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
}
static ssize_t sysfs_write(struct kobject *kobj, struct kobj_attribute *attr, const char *buf,ssize_t
{
}
static struct kobj_attribute my_sysfs_read =__ATTR(read, S_IRUGO, sysfs_read, NULL);
static struct kobj_attribute my_sysfs_write =__ATTR(write, S_IWUGO, NULL,sysfs_write);
static struct attribute *my_sysfs_test[] = {
};
static struct attribute_group my_attr_group = {
};
static int sysfs_status = 0 ;
struct kobject *soc_kobj = NULL;
int helloworld_init(void)
{
err_soc_sysfs_create:
err_board_obj:
}
void helloworld_exit(void)
{
}
MODULE_AUTHOR("vincent wu");
MODULE_LICENSE("Dual BSD/GPL");
module_init(helloworld_init);
module_exit(helloworld_exit);
// End------------------------------------------------------------------------
使用:
1.编译,insmod 驱动。
2.cd /sys ,发现多了一个创建的"my_sysfs_test"目录。
3.cd my_sysfs_test,发现多了两个创建的"read","write"目录。
4.cat read ,控制台输出"sysfs test read,created by vincent",这里实际会调用上面的sysfs_read函数。
5.echo hi sysfs > write ,这里实际会调用上面的sysfs_write函数输出。