1. 写法A:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73static ssize_t xxx_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf,"show somethingn"); } static ssize_t xxx_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { #if 1 //字符串判断 char on = *buf; if(on == '0'){ printk("to do something An"); } if(on == '1'){ printk("to do something Bn"); } #else //字符转int 判断 unsigned long value; int ret; ret = strict_strtoul(buf,10,&value);//strtoul(buf,10,&value); //或者 str 转 unsigned int //unsigned int cmd; //ret = kstrtouint(buf,10,&cmd); // if(ret){ return ret; } switch((int)value){ case 0: printk("to do something An"); break; case 1: printk("to do something Bn"); break; case 2: printk("to do something Cn"); break; default: printk("inval param.") } #endif return count; } static struct device_attribute xxx_dev_attr = { .attr = { .name = "xxx_state", .mode = S_IRWXU|S_IRWXG|S_IRWXO, }, .show = xxx_show, .store = xxx_store, }; static int xxx_probe(struct platform_device *pdev) { int ret = 0; ... //创建设备操控文件节点 ret = device_create_file(&(pdev->dev), &xxx_dev_attr); if (ret) { printk("[xxx_probe] sys file creation failedn"); } } static int xxx_remove(struct platform_device *pdev) { ... device_remove_file(&pdev->dev,&xxx_dev_attr); return 0; }
2. 写法B:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64static ssize_t xxx_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf,"show somethingn"); } static ssize_t xxx_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { #if 1 //字符串判断 char on = *buf; if(on == '0'){ printk("to do something An"); } if(on == '1'){ printk("to do something Bn"); } #else //字符转int 判断 unsigned long value; int ret; ret = strict_strtoul(buf,10,&value) if(ret){ return ret; } switch((int)value){ case 0: printk("to do something An"); break; case 1: printk("to do something Bn"); break; case 2: printk("to do something Cn"); break; default: printk("inval param.") } #endif return count; } //DEVICE_ATTR声明 static DEVICE_ATTR(xxx_state,S_IRWXU|S_IRWXG|S_IRWXO,xxx_show,xxx_store); static int xxx_probe(struct platform_device *pdev) { int ret = 0; ... //创建设备操控文件节点 ret = device_create_file(&(pdev->dev), &dev_attr_xxx_state); if (ret) { printk("[xxx_probe] sys file creation failedn"); } } static int xxx_remove(struct platform_device *pdev) { ... device_remove_file(&pdev->dev,&dev_attr_xxx_state); return 0; }
最后
以上就是老实小虾米最近收集整理的关于Linux dev_attr 设备文件操作的全部内容,更多相关Linux内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复