character_device_create.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Automatically create the device under /dev on insmod, and remove on rmmod.
  3. https://stackoverflow.com/questions/5970595/how-to-create-a-device-node-from-the-init-module-code-of-a-linux-kernel-module/45531867#45531867
  4. */
  5. #include <linux/cdev.h>
  6. #include <linux/device.h>
  7. #include <linux/fs.h> /* register_chrdev, unregister_chrdev */
  8. #include <linux/module.h>
  9. #include <linux/seq_file.h> /* seq_read, seq_lseek, single_release */
  10. #define NAME "lkmc_character_device_create"
  11. static int major = -1;
  12. static struct cdev mycdev;
  13. static struct class *myclass = NULL;
  14. static int show(struct seq_file *m, void *v)
  15. {
  16. seq_printf(m, "abcd");
  17. return 0;
  18. }
  19. static int open(struct inode *inode, struct file *file)
  20. {
  21. return single_open(file, show, NULL);
  22. }
  23. static const struct file_operations fops = {
  24. .llseek = seq_lseek,
  25. .open = open,
  26. .owner = THIS_MODULE,
  27. .read = seq_read,
  28. .release = single_release,
  29. };
  30. static void cleanup(int device_created)
  31. {
  32. if (device_created) {
  33. device_destroy(myclass, major);
  34. cdev_del(&mycdev);
  35. }
  36. if (myclass)
  37. class_destroy(myclass);
  38. if (major != -1)
  39. unregister_chrdev_region(major, 1);
  40. }
  41. static int myinit(void)
  42. {
  43. int device_created = 0;
  44. /* cat /proc/devices */
  45. if (alloc_chrdev_region(&major, 0, 1, NAME "_proc") < 0)
  46. goto error;
  47. /* ls /sys/class */
  48. if ((myclass = class_create(THIS_MODULE, NAME "_sys")) == NULL)
  49. goto error;
  50. /* ls /dev/ */
  51. if (device_create(myclass, NULL, major, NULL, NAME "_dev") == NULL)
  52. goto error;
  53. device_created = 1;
  54. cdev_init(&mycdev, &fops);
  55. if (cdev_add(&mycdev, major, 1) == -1)
  56. goto error;
  57. return 0;
  58. error:
  59. cleanup(device_created);
  60. return -1;
  61. }
  62. static void myexit(void)
  63. {
  64. cleanup(1);
  65. }
  66. module_init(myinit)
  67. module_exit(myexit)
  68. MODULE_LICENSE("GPL");