LINUX内核 DEVICE_ATTR与cat echo命令 直接读写调用Kernel测试方法

本文介绍了Linux内核中sysfs文件系统接口的创建过程,重点讲解DEVICE_ATTR宏的使用方法,并通过一个振动马达控制驱动的例子展示了如何实现sysfs接口的读写功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


sysfs接口函数的建立_DEVICE_ATTR  【转】

出自:http://blog.youkuaiyun.com/manshq163com/article/details/7848714

2012-05-09 11:36:46|  分类:linux文件系统 |  标签:device_attr  sysfs接口函数  |字号 订阅

 
 

说道sysfs接口,就不得不提到函数宏 DEVICE_ATTR,原型是

#define DEVICE_ATTR(_name, _mode, _show, _store) \

struct device_attribute dev_attr_##_name = __ATTR(_name, _mode, _show, _store)

函数宏DEVICE_ATTR内封装的是__ATTR(_name,_mode,_show,_stroe)方法

_show:表示的是读方法,

_stroe表示的是写方法。

 

当然_ATTR不是独生子女,他还有一系列的姊妹__ATTR_RO宏只有读方法,__ATTR_NULL等等

如对设备的使用        DEVICE_ATTR   

对驱动使用               DRIVER_ATTR

对总线使用               BUS_ATTR 

对类别 (class) 使用  CLASS_ATTR

这四个高级的宏来自于<include/linux/device.h> 

DEVICE_ATTR  宏声明有四个参数,分别是名称、权限位、读函数、写函数。其中读函数和写函数是读写功能函数的函数名。

如果你完成了DEVICE_ATTR函数宏的填充,下面就需要创建接口了

例如:

    static DEVICE_ATTR(polling, S_IRUGO | S_IWUSR, show_polling, set_polling);
    static struct attribute *dev_attrs[] = {
            &dev_attr_polling.attr,
            NULL,
    };

当你想要实现的接口名字是polling的时候,需要实现结构体struct attribute *dev_attrs[]

其中成员变量的名字必须是&dev_attr_polling.attr

然后再封装

    static struct attribute_group dev_attr_grp = {
            .attrs = dev_attrs,
    };

在利用 sysfs_create_group(&pdev->dev.kobj, &dev_attr_grp);创建接口

       通过以上简单的三个步骤,就可以在adb shell 终端查看到接口了。当我们将数据 echo 到接口中时,在上层实际上完成了一次 write 操作,对应到 kernel ,调用了驱动中的 “store”。同理,当我们cat 一个 接口时则会调用 “show” 。到这里,只是简单的建立了 android 层到 kernel 的桥梁,真正实现对硬件操作的,还是在 "show" 和 "store" 中完成的。

 

       其实呢?!用个proc文件系统的就知道,这个就和proc中的write和read一样的,以我的理解:proc有点老了,以后肯定会大量使用attribute,proc好比是Windows XP,attribute就像是Windows Seven
 
 
 
 
/****************************************下面是内核驱动例子  这样就比较清晰了****************/
复制代码
  1 #include <linux/io.h>
  2 #include <linux/gpio.h>
  3 #include <plat/gpio-cfg.h>
  4 #include <mach/regs-gpio.h>
  5 #include <linux/module.h>
  6 #include <linux/delay.h>
  7 #include <linux/platform_device.h>
  8 #include <linux/workqueue.h>
  9 
 10 //#include <mach/gpio-v8.h>
 11 
 12 /* Variables */
 13 static struct delayed_work vib_delayed_work;
 14 
 15 /* Definitions */
 16 #define VIB_TEST    0
 17 
 18 #define GPIO_VIBCTL        EXYNOS4_GPD0(0)
 19 
 20 #define CFG_VIB_CTRL    do {\
 21     gpio_request(GPIO_VIBCTL, "MOTOR_PWM");\
 22     s3c_gpio_cfgpin(GPIO_VIBCTL,S3C_GPIO_OUTPUT);\
 23     s3c_gpio_setpull(GPIO_VIBCTL,S3C_GPIO_PULL_NONE);\
 24 } while(0)
 25 
 26 #define VIB_START do {\
 27     gpio_set_value(GPIO_VIBCTL, 1);\
 28 } while(0)
 29 
 30 #define VIB_STOP do {\
 31     gpio_set_value(GPIO_VIBCTL, 0);\
 32 } while(0)
 33 
 34 #define RELEASE_VIB do {\
 35     gpio_free(GPIO_VIBCTL);\
 36 } while(0)
 37 
 38 #ifndef CONFIG_TC4_DVT
 39  #define USE_MOTOR_8997
 40 #else
 41  #undef USE_MOTOR_8997
 42 #endif
 43 
 44 #ifdef USE_MOTOR_8997
 45 extern void motor8997_on(int on);
 46 #endif
 47 
 48 /* Functions */
 49 static void vib_delayed_work_func(struct work_struct *work)
 50 {
 51 #ifdef USE_MOTOR_8997
 52     motor8997_on(0);
 53 #else
 54     VIB_STOP;
 55 #endif
 56 }
 57 
 58 int strtoint(const char *str,int len)
 59 {
 60     int result = 0;
 61     int i = 0;
 62     char c;
 63     while(i <= len-1)
 64     {   
 65         c = str[i++];
 66         if(c<'0' || c>'9')
 67             break;
 68         result = 10*result + c - '0';
 69     }
 70     return result;
 71 }
 72 
 73 static ssize_t vib_show(struct device *dev,
 74         struct device_attribute *attr, char *buf)
 75 {
 76     return printk("write a number in to vibrate\n");
 77 }
 78 
 79 static ssize_t vib_store(struct device *dev,
 80         struct device_attribute *attr,
 81         const char *buf, size_t count)
 82 {
 83     int retval;
 84     int value;
 85     value = strtoint(buf,count);
 86 #if VIB_TEST
 87     printk("count:%d, buf:%s",count,buf);
 88     printk("inv:%d ms\n",value);
 89 #endif
 90     retval = count;
 91     if(value)
 92     {
 93 #ifdef USE_MOTOR_8997
 94         motor8997_on(1);
 95 #else
 96         VIB_START;
 97 #endif
 98         schedule_delayed_work(&vib_delayed_work, msecs_to_jiffies(value));
 99     }
100     else
101     {
102 #ifdef USE_MOTOR_8997
103         motor8997_on(0);
104 #else
105         VIB_STOP;
106 #endif
107     }
108     return retval;
109 }
110 
111 /*
112  * sysfs: /sys/devices/platform/s5p-vib
113  * usage: echo ms > /sys/devices/platform/s5p-vib/vib
114  */
115 static DEVICE_ATTR(vib, S_IRUGO | S_IWUSR, vib_show, vib_store);
116 
117 static int __devinit s3c_vib_probe(struct platform_device *pdev)
118 {
119     int err;
120     err = device_create_file(&pdev->dev, &dev_attr_vib);
121     if (err)
122         goto error1;
123 
124     /* delayed work */
125     INIT_DELAYED_WORK(&vib_delayed_work, vib_delayed_work_func);
126 
127     CFG_VIB_CTRL;
128 
129 #if VIB_TEST
130 #ifdef USE_MOTOR_8997
131     motor8997_on(1);
132 #else
133     VIB_START;
134 #endif
135     schedule_delayed_work(&vib_delayed_work, msecs_to_jiffies(1000));
136 #endif
137     printk("vibrator probe success\n");
138 
139     return 0;
140 
141 error1:
142     return err;
143 }
144 
145 static int __devexit s3c_vib_remove(struct platform_device *dev)
146 {
147     RELEASE_VIB;
148     return 0;
149 }
150 
151 #ifdef CONFIG_PM
152 static int s3c_vib_suspend(struct platform_device *pdev, pm_message_t state)
153 {
154 #ifdef USE_MOTOR_8997
155     motor8997_on(0);
156 #else
157     VIB_STOP;
158 #endif
159     return 0;
160 }
161 
162 static int s3c_vib_resume(struct platform_device *pdev)
163 {
164     return 0;
165 }
166 #else
167 #define s3c_vib_suspend NULL
168 #define s3c_vib_resume  NULL
169 #endif
170 
171 static struct platform_driver s5p_vib_driver = {
172     .probe        = s3c_vib_probe,
173     .remove        = __devexit_p(s3c_vib_remove),
174     .suspend    = s3c_vib_suspend,
175     .resume        = s3c_vib_resume,
176     .driver        = {
177         .name    = "s5p-vib",
178         .owner    = THIS_MODULE,
179     },
180 };
181 
182 static char __initdata banner[] = "S5P VIBRATOR\n";
183 
184 static int __init s3c_vib_init(void)
185 {
186     printk(banner);
187     return platform_driver_register(&s5p_vib_driver);
188 }
189 
190 static void __exit s3c_vib_exit(void)
191 {
192     printk("%s()\n",__FUNCTION__);
193     platform_driver_unregister(&s5p_vib_driver);
194 }
195 
196 module_init(s3c_vib_init);
197 module_exit(s3c_vib_exit);
/* * 安装模块(带参数) * sudo insmod char_dev.ko cap=1 * * 查看设备节点 * ls -l /dev/my_char_dev * * 测试写入设备 * echo "Hello Kernel World" | sudo tee /dev/my_char_dev * * 查看内核日志(需要root权限) * sudo dmesg | grep my_char_dev * * 卸载模块 * sudo rmmod char_dev */ #include <linux/module.h> #include <linux/fs.h> #include <linux/cdev.h> #include <linux/device.h> #include <linux/uaccess.h> #include <linux/ctype.h> #include <linux/mutex.h> #define DEVICE_NAME "my_char_dev" #define MAX_BUF_LEN 1024 /* 模块参数 */ static int cap = 0; module_param(cap, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(cap, "Convert to uppercase if set to 1 (default=0)"); /* 共享数据结构 */ static struct { char buffer[MAX_BUF_LEN]; // 数据缓冲区 size_t data_len; // 有效数据长度 struct mutex lock; // 互斥锁 } dev_data; static dev_t dev_num; static struct cdev my_cdev; static struct class *my_class; static struct device *my_device; /* 设备打开函数 */ static int device_open(struct inode *inode, struct file *file) { return 0; } /* 设备释放函数 */ static int device_release(struct inode *inode, struct file *file) { return 0; } /* 设备写入函数 */ static ssize_t device_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) { size_t len = (count > MAX_BUF_LEN - 1) ? MAX_BUF_LEN - 1 : count; int i = 0; // 加锁保护共享数据 mutex_lock(&dev_data.lock); /* 从用户空间复制数据 */ if (copy_from_user(dev_data.buffer, buf, len)) { mutex_unlock(&dev_data.lock); return -EFAULT; } dev_data.buffer[len] = '\0'; // 确保字符串终止 dev_data.data_len = len; // 记录有效长度 /* 根据cap参数进行大小写转换 */ if (cap) { for (i = 0; dev_data.buffer[i]; i++) { dev_data.buffer[i] = toupper(dev_data.buffer[i]); } } printk(KERN_INFO "my_char_dev: Received: %s\n", dev_data.buffer); mutex_unlock(&dev_data.lock); // 解锁 return len; } /* 设备读取函数 */ static ssize_t device_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) { ssize_t retval = 0; // 加锁保护共享数据 mutex_lock(&dev_data.lock); if (*f_pos >= dev_data.data_len) { mutex_unlock(&dev_data.lock); return 0; // 文件结尾 } // 计算剩余可读数据量 size_t remaining = dev_data.data_len - *f_pos; size_t to_copy = (count < remaining) ? count : remaining; // 复制数据到用户空间 if (copy_to_user(buf, dev_data.buffer + *f_pos, to_copy)) { mutex_unlock(&dev_data.lock); return -EFAULT; } *f_pos += to_copy; // 更新文件位置 retval = to_copy; mutex_unlock(&dev_data.lock); // 解锁 return retval; } /* 定义设备支持的操作 */ static const struct file_operations fops = { .owner = THIS_MODULE, .open = device_open, .release = device_release, .write = device_write, .read = device_read, // 添加read支持 }; /* 模块初始化函数 */ static int __init char_dev_init(void) { /* 初始化共享数据 */ mutex_init(&dev_data.lock); // 初始化互斥锁 dev_data.data_len = 0; dev_data.buffer[0] = '\0'; /* 动态分配设备号 */ if (alloc_chrdev_region(&dev_num, 0, 1, DEVICE_NAME) < 0) return -1; /* 初始化字符设备 */ cdev_init(&my_cdev, &fops); if (cdev_add(&my_cdev, dev_num, 1) < 0) goto err_cdev; /* 创建设备类 */ my_class = class_create(THIS_MODULE, "my_char_class"); if (IS_ERR(my_class)) goto err_class; /* 创建设备节点 */ my_device = device_create(my_class, NULL, dev_num, NULL, DEVICE_NAME); if (IS_ERR(my_device)) goto err_device; /* 设置设备权限(所有用户可读写) */ device_create_file(my_device, &dev_attr_cap); // 可选:添加cap属性文件 printk(KERN_INFO "my_char_dev: Module loaded, cap=%d\n", cap); return 0; /* 错误处理 */ err_device: class_destroy(my_class); err_class: cdev_del(&my_cdev); err_cdev: unregister_chrdev_region(dev_num, 1); return -1; } /* 模块退出函数 */ static void __exit char_dev_exit(void) { device_destroy(my_class, dev_num); class_destroy(my_class); cdev_del(&my_cdev); unregister_chrdev_region(dev_num, 1); mutex_destroy(&dev_data.lock); // 销毁互斥锁 printk(KERN_INFO "my_char_dev: Module unloaded\n"); } module_init(char_dev_init); module_exit(char_dev_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Your Name"); MODULE_DESCRIPTION("Advanced char device driver with case conversion"); 这段代码make以后发生以下错误: xyc@xyc-virtual-machine:~/VSCode/embedded-linux/char_device$ make make -C /lib/modules/4.15.0-213-generic/build M=/home/xyc/VSCode/embedded-linux/char_device modules make[1]: Entering directory '/usr/src/linux-headers-4.15.0-213-generic' CC [M] /home/xyc/VSCode/embedded-linux/char_device/char_dev.o /home/xyc/VSCode/embedded-linux/char_device/char_dev.c: In function ‘device_read’: /home/xyc/VSCode/embedded-linux/char_device/char_dev.c:103:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement] size_t remaining = dev_data.data_len - *f_pos; ^~~~~~ /home/xyc/VSCode/embedded-linux/char_device/char_dev.c: In function ‘char_dev_init’: /home/xyc/VSCode/embedded-linux/char_device/char_dev.c:156:36: error: ‘dev_attr_cap’ undeclared (first use in this function); did you mean ‘setattr_copy’? device_create_file(my_device, &dev_attr_cap); // 可选:添加cap属性文件 ^~~~~~~~~~~~ setattr_copy /home/xyc/VSCode/embedded-linux/char_device/char_dev.c:156:36: note: each undeclared identifier is reported only once for each function it appears in scripts/Makefile.build:340: recipe for target '/home/xyc/VSCode/embedded-linux/char_device/char_dev.o' failed make[2]: *** [/home/xyc/VSCode/embedded-linux/char_device/char_dev.o] Error 1 Makefile:1596: recipe for target '_module_/home/xyc/VSCode/embedded-linux/char_device' failed make[1]: *** [_module_/home/xyc/VSCode/embedded-linux/char_device] Error 2 make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-213-generic' Makefile:5: recipe for target 'all' failed make: *** [all] Error 2 这是什么问题
最新发布
08-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值