字符设备驱动是 Linux 驱动开发的基础,通过 file_operations 结构体向用户态暴露读写接口。
一、驱动骨架
c
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
static int major;
static struct cdev my_cdev;
static ssize_t my_read(struct file *f, char __user *buf, size_t len, loff_t *off) {
return 0;
}
static struct file_operations my_fops = {
.owner = THIS_MODULE,
.read = my_read,
};
static int __init my_init(void) {
alloc_chrdev_region(&dev, 0, 1, "mydev");
cdev_init(&my_cdev, &my_fops);
cdev_add(&my_cdev, dev, 1);
return 0;
}
module_init(my_init);
MODULE_LICENSE("GPL");二、用户态与内核态数据交换
必须使用 copy_to_user / copy_from_user 而非直接解引用用户指针,否则可能引发内核崩溃或安全漏洞。开发时建议在虚拟机中测试,避免驱动缺陷导致宿主机宕机。