procfs2.c 2.5 KB

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