charDevice.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <linux/module.h>
  2. #include <linux/init.h>
  3. #include <linux/fs.h> // 包含 file_operations 和 register_chrdev 函数
  4. #include <linux/cdev.h> // 包含 cdev 相关结构和函数
  5. #define DEVICE_NAME "charDevice3"
  6. // 文件操作函数声明
  7. static int dev_open(struct inode *inode, struct file *file);
  8. static int dev_release(struct inode *inode, struct file *file);
  9. static ssize_t dev_read(struct file *file, char __user *buf, size_t count, loff_t *ppos);
  10. static ssize_t dev_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos);
  11. // 文件操作结构
  12. static struct file_operations fops = {
  13. .owner = THIS_MODULE,
  14. .open = dev_open,
  15. .release = dev_release,
  16. .read = dev_read,
  17. .write = dev_write,
  18. };
  19. // 文件操作函数的实现
  20. static int dev_open(struct inode *inode, struct file *file) {
  21. pr_info("Device opened\n");
  22. return 0;
  23. }
  24. static int dev_release(struct inode *inode, struct file *file) {
  25. pr_info("Device closed\n");
  26. return 0;
  27. }
  28. static ssize_t dev_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) {
  29. pr_info("Reading from device\n");
  30. return 0; // 假设返回 0 表示读到文件结尾
  31. }
  32. static ssize_t dev_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) {
  33. pr_info("Writing to device\n");
  34. return count; // 返回写入的字节数
  35. }
  36. static int __init helloworld_init(void) {
  37. int retvalue;
  38. // 注册字符设备,使用主设备号 200
  39. retvalue = register_chrdev(200, DEVICE_NAME, &fops);
  40. if (retvalue < 0) {
  41. pr_err("Failed to register char device\n");
  42. return -EIO;
  43. }
  44. pr_info("Hello world initialization!\n");
  45. return 0;
  46. }
  47. static void __exit helloworld_exit(void) {
  48. // 注销字符设备驱动
  49. unregister_chrdev(200, DEVICE_NAME);
  50. pr_info("Hello world exit\n");
  51. }
  52. module_init(helloworld_init);
  53. module_exit(helloworld_exit);
  54. MODULE_LICENSE("GPL");
  55. MODULE_AUTHOR("John Madieu <john.madieu@gmail.com>");
  56. MODULE_DESCRIPTION("Linux kernel module skeleton");