Ubuntu 下创建设备节点的完整驱动示例
下面是一个完整的字符设备驱动示例,它会在 /dev
目录下创建名为 mydevice
的设备节点,并实现基本的文件操作接口。
1. 驱动代码 (chardev.c)
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#define DEVICE_NAME "mydevice"
#define CLASS_NAME "mymodule"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Character device driver example with /dev node");
static int major_number;
static struct class* dev_class = NULL;
static struct device* dev_device = NULL;
static struct cdev my_cdev;
// 设备缓冲区
static char *device_buffer;
static int buffer_size = 1024;
static int buffer_offset = 0;
// 文件操作函数原型
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char __user *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char __user *, size_t, loff_t *);
// 文件操作结构体
static struct file_operations fops = {
.open = device_open,
.release = device_release,
.read = device_read,
.write = device_write,
};
// 打开设备
static int device_open(struct inode *inode, struct file *file)
{
printk(KERN_INFO "Device opened\n");
return 0;
}
// 关闭设备
static int device_release(struct inode *inode, struct file *file)
{
printk(KERN_INFO "Device closed\n");
return 0;
}
// 读取设备
static ssize_t device_read(struct file *filp, char __user *buf, size_t len, loff_t *offset)
{
int bytes_to_read;
int bytes_read = 0;
if (*offset >= buffer_offset