| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- #include <linux/module.h>
- #include <linux/init.h>
- #include <linux/fs.h> // 包含 file_operations 和 register_chrdev 函数
- #include <linux/cdev.h> // 包含 cdev 相关结构和函数
- #define DEVICE_NAME "charDevice3"
- // 文件操作函数声明
- static int dev_open(struct inode *inode, struct file *file);
- static int dev_release(struct inode *inode, struct file *file);
- static ssize_t dev_read(struct file *file, char __user *buf, size_t count, loff_t *ppos);
- static ssize_t dev_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos);
- // 文件操作结构
- static struct file_operations fops = {
- .owner = THIS_MODULE,
- .open = dev_open,
- .release = dev_release,
- .read = dev_read,
- .write = dev_write,
- };
- // 文件操作函数的实现
- static int dev_open(struct inode *inode, struct file *file) {
- pr_info("Device opened\n");
- return 0;
- }
- static int dev_release(struct inode *inode, struct file *file) {
- pr_info("Device closed\n");
- return 0;
- }
- static ssize_t dev_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) {
- pr_info("Reading from device\n");
- return 0; // 假设返回 0 表示读到文件结尾
- }
- static ssize_t dev_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) {
- pr_info("Writing to device\n");
- return count; // 返回写入的字节数
- }
- static int __init helloworld_init(void) {
- int retvalue;
- // 注册字符设备,使用主设备号 200
- retvalue = register_chrdev(200, DEVICE_NAME, &fops);
- if (retvalue < 0) {
- pr_err("Failed to register char device\n");
- return -EIO;
- }
- pr_info("Hello world initialization!\n");
- return 0;
- }
- static void __exit helloworld_exit(void) {
- // 注销字符设备驱动
- unregister_chrdev(200, DEVICE_NAME);
- pr_info("Hello world exit\n");
- }
- module_init(helloworld_init);
- module_exit(helloworld_exit);
- MODULE_LICENSE("GPL");
- MODULE_AUTHOR("John Madieu <john.madieu@gmail.com>");
- MODULE_DESCRIPTION("Linux kernel module skeleton");
|