| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- #include <linux/module.h>
- #include <linux/fs.h>
- #include <linux/cdev.h>
- #include <linux/uaccess.h>
- #define DEVICE_NAME "my_char_device"
- #define CLASS_NAME "my_char_class"
- static int majorNumber; // 设备号
- static struct class* myCharClass = NULL; // 设备类
- // 打开设备
- static int dev_open(struct inode *inodep, struct file *filep) {
- printk(KERN_INFO "my_char_device: Device opened\n");
- return 0;
- }
- // 读取设备
- static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset) {
- printk(KERN_INFO "my_char_device: Read from device\n");
- return 0; // 返回0表示没有读取任何数据
- }
- // 写入设备
- static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, loff_t *offset) {
- printk(KERN_INFO "my_char_device: Write to device\n");
- return len; // 返回写入的字节数
- }
- // 释放设备
- static int dev_release(struct inode *inodep, struct file *filep) {
- printk(KERN_INFO "my_char_device: Device closed\n");
- return 0;
- }
- // 文件操作结构体
- static struct file_operations fops = {
- .owner = THIS_MODULE,
- .open = dev_open,
- .read = dev_read,
- .write = dev_write,
- .release = dev_release,
- };
- // 模块初始化
- static int __init my_char_init(void) {
- // 自动申请设备号
- majorNumber = register_chrdev(0, DEVICE_NAME, &fops);
- if (majorNumber < 0) {
- printk(KERN_ALERT "my_char_device failed to register a major number\n");
- return majorNumber;
- }
- printk(KERN_INFO "my_char_device: registered correctly with major number %d\n", majorNumber);
- // 创建设备类
- myCharClass = class_create(THIS_MODULE, CLASS_NAME);
- if (IS_ERR(myCharClass)) {
- unregister_chrdev(majorNumber, DEVICE_NAME);
- printk(KERN_ALERT "Failed to register device class\n");
- return PTR_ERR(myCharClass);
- }
- // 创建设备
- device_create(myCharClass, NULL, MKDEV(majorNumber, 0), NULL, DEVICE_NAME);
- printk(KERN_INFO "my_char_device: device class created correctly\n");
- return 0;
- }
- // 模块退出
- static void __exit my_char_exit(void) {
- device_destroy(myCharClass, MKDEV(majorNumber, 0)); // 删除设备
- class_unregister(myCharClass); // 取消设备类注册
- class_destroy(myCharClass); // 销毁设备类
- unregister_chrdev(majorNumber, DEVICE_NAME); // 注销设备号
- printk(KERN_INFO "my_char_device: Goodbye from the LKM!\n");
- }
- module_init(my_char_init);
- module_exit(my_char_exit);
- MODULE_LICENSE("GPL");
- MODULE_AUTHOR("Your Name");
- MODULE_DESCRIPTION("A simple Linux char driver");
- MODULE_VERSION("0.1");
|