1
0

procfs2.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /**
  2. * procfs2.c - create a "file" in /proc
  3. *
  4. */
  5. #include <linux/module.h> /* Specifically, a module */
  6. #include <linux/kernel.h> /* We're doing kernel work */
  7. #include <linux/proc_fs.h> /* Necessary because we use the proc fs */
  8. #include <linux/uaccess.h> /* for copy_from_user */
  9. #define PROCFS_MAX_SIZE 1024
  10. #define PROCFS_NAME "buffer1k"
  11. /**
  12. * This structure hold information about the /proc file
  13. *
  14. */
  15. static struct proc_dir_entry *Our_Proc_File;
  16. /**
  17. * The buffer used to store character for this module
  18. *
  19. */
  20. static char procfs_buffer[PROCFS_MAX_SIZE];
  21. /**
  22. * The size of the buffer
  23. *
  24. */
  25. static unsigned long procfs_buffer_size = 0;
  26. /**
  27. * This function is called then the /proc file is read
  28. *
  29. */
  30. ssize_t procfile_read(struct file *filePointer,char *buffer,
  31. size_t buffer_length, loff_t * offset)
  32. {
  33. int ret=0;
  34. if(strlen(buffer) ==0) {
  35. pr_info("procfile read %s\n",filePointer->f_path.dentry->d_name.name);
  36. ret=copy_to_user(buffer,"HelloWorld!\n",sizeof("HelloWorld!\n"));
  37. ret=sizeof("HelloWorld!\n");
  38. }
  39. return ret;
  40. }
  41. /**
  42. * This function is called with the /proc file is written
  43. *
  44. */
  45. static ssize_t procfile_write(struct file *file, const char *buff,
  46. size_t len, loff_t *off)
  47. {
  48. procfs_buffer_size = len;
  49. if (procfs_buffer_size > PROCFS_MAX_SIZE)
  50. procfs_buffer_size = PROCFS_MAX_SIZE;
  51. if (copy_from_user(procfs_buffer, buff, procfs_buffer_size))
  52. return -EFAULT;
  53. procfs_buffer[procfs_buffer_size] = '\0';
  54. return procfs_buffer_size;
  55. }
  56. static const struct proc_ops proc_file_fops = {
  57. .proc_read = procfile_read,
  58. .proc_write = procfile_write,
  59. };
  60. /**
  61. *This function is called when the module is loaded
  62. *
  63. */
  64. int init_module()
  65. {
  66. Our_Proc_File = proc_create(PROCFS_NAME,0644,NULL,&proc_file_fops);
  67. if(NULL==Our_Proc_File) {
  68. proc_remove(Our_Proc_File);
  69. pr_alert("Error:Could not initialize /proc/%s\n",PROCFS_NAME);
  70. return -ENOMEM;
  71. }
  72. pr_info("/proc/%s created\n", PROCFS_NAME);
  73. return 0;
  74. }
  75. /**
  76. *This function is called when the module is unloaded
  77. *
  78. */
  79. void cleanup_module()
  80. {
  81. proc_remove(Our_Proc_File);
  82. pr_info("/proc/%s removed\n", PROCFS_NAME);
  83. }
  84. MODULE_LICENSE("GPL");