热门内容

公众号"MAKE1"

获取行业最新资讯

请扫码添加

专业客服企业微信

linux sys属性节点创建

简介

linux sys属性节点创建

 

  1. #include <linux/module.h>
  2. #include <linux/slab.h>
  3. #include <linux/kobject.h>
  4. #include <linux/platform_device.h>
  5.  
  6. struct att_dev{
  7. struct platform_device *pdev;
  8. struct kobject *kobj;
  9. };
  10.  
  11. static ssize_t att_store(struct device *dev,
  12. struct device_attribute *attr,
  13. const char *buf, size_t count)
  14. {
  15. printk("echo debug bufn");
  16.  
  17. return count;
  18. }
  19.  
  20. static ssize_t att_show(struct device *dev,
  21. struct device_attribute *attr,
  22. char *buf)
  23. {
  24. printk("cat debug bufn");
  25. return 0;
  26. }
  27. static DEVICE_ATTR(test,0777,att_show,att_store);
  28.  
  29. static struct att_dev *dev = NULL;
  30.  
  31. static __devinit int att_probe(struct platform_device *ppdev){
  32. int ret;
  33.  
  34. dev->kobj = kobject_create_and_add("attkobj", NULL); //( 节点位置?????)
  35. if(dev->kobj == NULL){
  36. ret = -ENOMEM;
  37. goto kobj_err;
  38. }
  39.  
  40. ret = sysfs_create_file(&dev->pdev->dev.kobj,&dev_attr_test.attr);
  41. if(ret < 0){
  42. goto file_err;
  43. }
  44. return 0;
  45.  
  46. file_err:
  47. kobject_del(dev->kobj);
  48. kobj_err:
  49. return ret;
  50. }
  51.  
  52. static struct platform_driver att_driver = {
  53. .probe = att_probe,
  54. .driver = {
  55. .owner = THIS_MODULE,
  56. .name = "att_test",
  57. },
  58. };
  59.  
  60. static int __init att_init(void)
  61. {
  62. int ret;
  63.  
  64. dev = kzalloc(sizeof(struct att_dev),GFP_KERNEL);
  65. if(dev == NULL){
  66. printk("%s get dev memory errorn",__func__);
  67. return -ENOMEM;
  68. }
  69.  
  70. dev->pdev = platform_device_register_simple("att_test", -1, NULL, 0);
  71. if(IS_ERR(dev->pdev)){
  72. PTR_ERR(dev->pdev);
  73. printk("%s pdev errorn",__func__);
  74. return -1;
  75. }
  76.  
  77. ret = platform_driver_register(&att_driver);
  78. if(ret < 0){
  79. printk("%s register driver errorn",__func__);
  80. return ret;
  81. }
  82.  
  83. return 0;
  84. }
  85.  
  86. static void __exit att_exit(void)
  87. {
  88.  
  89. }
  90.  
  91. module_init(att_init);
  92. module_exit(att_exit);
  93. MODULE_LICENSE("GPL");
  94. MODULE_AUTHOR("driverSir");

Makefile原代码:

ifeq ($(KERNELRELEASE),)

#KERNEL_DIR:=/lib/modules/$(shell uname -r)/build/

KERNEL_DIR:=/usr/src/linux-headers-3.2.0-29-generic-pae

PWD:=$(shell pwd)

modules:

$(MAKE) -C $(KERNEL_DIR) M=$(PWD) modules

modules_install:

$(MAKE) -C $(KERNEL_DIR) M=$(PWD) modules_install

clean:

rm -rf .*.cmd *.ko *.o modules.order Module.symvers *mod.c

.PHONY: modules modules_install clean

else

modules-objs := att.o

obj-m := att.o

endif

 

安装之后/sys/devices/platform/att_test/test

echo 1 > test

cat test

dmesg之后会看到内核打印出

[ 424.793357] echo debug buf

[ 427.122139] cat debug buf

说明在echo 1 > test 时调用了att_store,cat test 的时候调用了att_show

0
 条评论
相关内容推荐