1.介绍
使用DEVICE_ATTR,可以实现驱动在sys目录自动创建文件,我们只需要实现show和store函数即可.
然后在应用层就能通过cat和echo命令来对sys创建出来的文件进行读写驱动设备,实现交互.
2.DEVICE_ATTR()宏定义
DEVICE_ATTR()定义位于include/linux/device.h中,定义如下所示:
#define DEVICE_ATTR(_name, _mode, _show, _store) struct device_attribute dev_attr_##_name = __ATTR(_name, _mode, _show, _store)
其中_mode定义如下:
也可以用S_IWUSR(用户可写),S_IRUSR(用户可读)等宏代替.
static ssize_t device_show(struct device *dev, struct device_attribute *attr, char *buf) //cat命令时,将会调用该函数
{ return buf; } static ssize_t device_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) //echo命令时,将会调用该函数. { return len; } static DEVICE_ATTR(my_device_test, S_IWUSR|S_IRUSR, device_show, device_store);
//定义一个名字为my_device_test的设备属性文件
最终将宏展开为:
struct device_attribute dev_attr_my_device_test ={ .attr = {.name = "my_device_test", .mode = S_IWUSR|S_IRUSR }, .show = show_my_device, .store = set_my_device, }
然后再通过device_create_file()或者sysfs_create_file()便来创建上面my_device_test设备文件.
3.使用示例
#include <board.h> #include <linux/module.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/regulator/consumer.h> #include <sound/soc.h> #include <sound/jack.h> static char mybuf[100]="123"; static ssize_t show_my_device(struct device *dev, struct device_attribute *attr, char *buf) //cat命令时,将会调用该函数 { return sprintf(buf, "%s\n", mybuf); } static ssize_t set_my_device(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) //echo命令时,将会调用该函数 { sprintf(mybuf, "%s", buf); return len; } static DEVICE_ATTR(my_device_test, S_IWUSR|S_IRUSR, show_my_device, set_my_device); //定义一个名字为my_device_test的设备属性文件 struct file_operations mytest_ops={ .owner = THIS_MODULE, }; static int major; static struct class *cls; static int mytest_init(void) { struct device *mydev; major=register_chrdev(0,"mytest", &mytest_ops); cls=class_create(THIS_MODULE, "mytest_class"); mydev = device_create(cls, 0, MKDEV(major,0),NULL,"mytest_device");
//创建mytest_device设备 if(sysfs_create_file(&(mydev->kobj), &dev_attr_my_device_test.attr)){
//在mytest_device设备目录下创建一个my_device_test属性文件 return -1;} return 0; } static void mytest_exit(void) { device_destroy(cls, MKDEV(major,0)); class_destroy(cls); unregister_chrdev(major, "mytest"); } module_init(mytest_init); module_exit(mytest_exit); MODULE_LICENSE("GPL");
Linux驱动 --static DEVICE_ATTR()函数
原文:https://www.cnblogs.com/vino-yu/p/14118812.html