使用proc接口例子【转】

本文转载自:http://blog.csdn.net/mike8825/article/details/52434666

在上一篇的使用sys接口来调试驱动的写完后,这里也将proc接口的例子贴出来。

proc.c的文件内容为

[plain] view plain copy
 
  1. #include <linux/module.h>  
  2. #include <linux/proc_fs.h>  
  3. #include <linux/seq_file.h>  
  4.   
  5. static int hello_proc_show(struct seq_file *m, void *v)  
  6. {  
  7.       seq_printf(m, "Hello proc! ");  
  8.       return 0;  
  9. }  
  10.   
  11. ssize_t test_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)  
  12. {  
  13.     unsigned int var;  
  14.     var=simple_strtoul(buffer,NULL,10);  
  15.     printk("var=%d ",var);  
  16.     return count;  
  17. }  
  18.   
  19. static int hello_proc_open(struct inode *inode, struct  file *file)  
  20. {  
  21.      return single_open(file, hello_proc_show, NULL);  
  22. }  
  23.   
  24. static const struct file_operations hello_proc_fops =   
  25. {  
  26.     .owner   = THIS_MODULE,  
  27.     .open    = hello_proc_open,  
  28.     .read    = seq_read,  
  29.     .write   = test_proc_write,  
  30.     .llseek  = seq_lseek,  
  31.     .release = single_release,  
  32. };  
  33.   
  34. static int __init hello_proc_init(void)  
  35. {  
  36.     proc_create("hello_proc", S_IRWXUGO, NULL, &hello_proc_fops);  
  37.     return 0;  
  38. }  
  39.   
  40. static void __exit hello_proc_exit(void)   
  41. {  
  42.      remove_proc_entry("hello_proc", NULL);  
  43. }  
  44.   
  45. MODULE_LICENSE("GPL");  
  46. module_init(hello_proc_init);  
  47. module_exit(hello_proc_exit);  

安装该驱动后,在proc下出现hello_proc文件,可通过echo和cat来读写文件。

[plain] view plain copy
 
  1. root@w-Lenovo-G470:/proc# ls -al hello_proc   
  2. -rwxrwxrwx 1 root root 0 9月   4 20:58 hello_proc  

该驱动在内核3.10之后的版本才可以用,内核3.10的的可参考http://blog.csdn.net/a_ran/article/details/37626765
原文地址:https://www.cnblogs.com/zzb-Dream-90Time/p/8167577.html