47.Linux-DEVICE_ATTR()介紹及使用示例
阿新 • • 發佈:2018-12-15
#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> staticchar 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");