newchrled.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/cdev.h>
  4. #include <linux/uaccess.h>
  5. #define DEVICE_NAME "my_char_device"
  6. #define CLASS_NAME "my_char_class"
  7. static int majorNumber; // 设备号
  8. static struct class* myCharClass = NULL; // 设备类
  9. // 打开设备
  10. static int dev_open(struct inode *inodep, struct file *filep) {
  11. printk(KERN_INFO "my_char_device: Device opened\n");
  12. return 0;
  13. }
  14. // 读取设备
  15. static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset) {
  16. printk(KERN_INFO "my_char_device: Read from device\n");
  17. return 0; // 返回0表示没有读取任何数据
  18. }
  19. // 写入设备
  20. static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, loff_t *offset) {
  21. printk(KERN_INFO "my_char_device: Write to device\n");
  22. return len; // 返回写入的字节数
  23. }
  24. // 释放设备
  25. static int dev_release(struct inode *inodep, struct file *filep) {
  26. printk(KERN_INFO "my_char_device: Device closed\n");
  27. return 0;
  28. }
  29. // 文件操作结构体
  30. static struct file_operations fops = {
  31. .owner = THIS_MODULE,
  32. .open = dev_open,
  33. .read = dev_read,
  34. .write = dev_write,
  35. .release = dev_release,
  36. };
  37. // 模块初始化
  38. static int __init my_char_init(void) {
  39. // 自动申请设备号
  40. majorNumber = register_chrdev(0, DEVICE_NAME, &fops);
  41. if (majorNumber < 0) {
  42. printk(KERN_ALERT "my_char_device failed to register a major number\n");
  43. return majorNumber;
  44. }
  45. printk(KERN_INFO "my_char_device: registered correctly with major number %d\n", majorNumber);
  46. // 创建设备类
  47. myCharClass = class_create(THIS_MODULE, CLASS_NAME);
  48. if (IS_ERR(myCharClass)) {
  49. unregister_chrdev(majorNumber, DEVICE_NAME);
  50. printk(KERN_ALERT "Failed to register device class\n");
  51. return PTR_ERR(myCharClass);
  52. }
  53. // 创建设备
  54. device_create(myCharClass, NULL, MKDEV(majorNumber, 0), NULL, DEVICE_NAME);
  55. printk(KERN_INFO "my_char_device: device class created correctly\n");
  56. return 0;
  57. }
  58. // 模块退出
  59. static void __exit my_char_exit(void) {
  60. device_destroy(myCharClass, MKDEV(majorNumber, 0)); // 删除设备
  61. class_unregister(myCharClass); // 取消设备类注册
  62. class_destroy(myCharClass); // 销毁设备类
  63. unregister_chrdev(majorNumber, DEVICE_NAME); // 注销设备号
  64. printk(KERN_INFO "my_char_device: Goodbye from the LKM!\n");
  65. }
  66. module_init(my_char_init);
  67. module_exit(my_char_exit);
  68. MODULE_LICENSE("GPL");
  69. MODULE_AUTHOR("Your Name");
  70. MODULE_DESCRIPTION("A simple Linux char driver");
  71. MODULE_VERSION("0.1");