procfs1.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * procfs1.c
  3. */
  4. #include <linux/kernel.h>
  5. #include <linux/module.h>
  6. #include <linux/proc_fs.h>
  7. #include <linux/uaccess.h>
  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_name "helloworld"
  13. struct proc_dir_entry *Our_Proc_File;
  14. ssize_t procfile_read(struct file *filePointer,
  15. char *buffer,
  16. size_t buffer_length,
  17. loff_t *offset)
  18. {
  19. char s[13] = "HelloWorld!\n";
  20. int len = sizeof(s);
  21. ssize_t ret = len;
  22. if (*offset >= len || copy_to_user(buffer, s, len)) {
  23. pr_info("copy_to_user failed\n");
  24. ret = 0;
  25. } else {
  26. pr_info("procfile read %s\n", filePointer->f_path.dentry->d_name.name);
  27. *offset += len;
  28. }
  29. return ret;
  30. }
  31. #ifdef HAVE_PROC_OPS
  32. static const struct proc_ops proc_file_fops = {
  33. .proc_read = procfile_read,
  34. };
  35. #else
  36. static const struct file_operations proc_file_fops = {
  37. .read = procfile_read,
  38. };
  39. #endif
  40. static int __init procfs1_init(void)
  41. {
  42. Our_Proc_File = proc_create(procfs_name, 0644, NULL, &proc_file_fops);
  43. if (NULL == Our_Proc_File) {
  44. proc_remove(Our_Proc_File);
  45. pr_alert("Error:Could not initialize /proc/%s\n", procfs_name);
  46. return -ENOMEM;
  47. }
  48. pr_info("/proc/%s created\n", procfs_name);
  49. return 0;
  50. }
  51. static void __exit procfs1_exit(void)
  52. {
  53. proc_remove(Our_Proc_File);
  54. pr_info("/proc/%s removed\n", procfs_name);
  55. }
  56. module_init(procfs1_init);
  57. module_exit(procfs1_exit);
  58. MODULE_LICENSE("GPL");