procfs2.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * procfs2.c - create a "file" in /proc
  3. *
  4. */
  5. #include <linux/kernel.h> /* We're doing kernel work */
  6. #include <linux/module.h> /* Specifically, a module */
  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,
  31. char *buffer,
  32. size_t buffer_length,
  33. loff_t *offset)
  34. {
  35. int ret = 0;
  36. if (strlen(buffer) == 0) {
  37. pr_info("procfile read %s\n", filePointer->f_path.dentry->d_name.name);
  38. ret = copy_to_user(buffer, "HelloWorld!\n", sizeof("HelloWorld!\n"));
  39. ret = sizeof("HelloWorld!\n");
  40. }
  41. return ret;
  42. }
  43. /**
  44. * This function is called with the /proc file is written
  45. *
  46. */
  47. static ssize_t procfile_write(struct file *file,
  48. const char *buff,
  49. size_t len,
  50. loff_t *off)
  51. {
  52. procfs_buffer_size = len;
  53. if (procfs_buffer_size > PROCFS_MAX_SIZE)
  54. procfs_buffer_size = PROCFS_MAX_SIZE;
  55. if (copy_from_user(procfs_buffer, buff, procfs_buffer_size))
  56. return -EFAULT;
  57. procfs_buffer[procfs_buffer_size] = '\0';
  58. return procfs_buffer_size;
  59. }
  60. static const struct proc_ops proc_file_fops = {
  61. .proc_read = procfile_read,
  62. .proc_write = procfile_write,
  63. };
  64. /**
  65. *This function is called when the module is loaded
  66. *
  67. */
  68. int init_module()
  69. {
  70. Our_Proc_File = proc_create(PROCFS_NAME, 0644, NULL, &proc_file_fops);
  71. if (NULL == Our_Proc_File) {
  72. proc_remove(Our_Proc_File);
  73. pr_alert("Error:Could not initialize /proc/%s\n", PROCFS_NAME);
  74. return -ENOMEM;
  75. }
  76. pr_info("/proc/%s created\n", PROCFS_NAME);
  77. return 0;
  78. }
  79. /**
  80. *This function is called when the module is unloaded
  81. *
  82. */
  83. void cleanup_module()
  84. {
  85. proc_remove(Our_Proc_File);
  86. pr_info("/proc/%s removed\n", PROCFS_NAME);
  87. }
  88. MODULE_LICENSE("GPL");