#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/mutex.h>
#include <linux/wait.h>
#define DEVICE_NAME "custom_dev"
#define BUFFER_SIZE 4096 // 可以根据需要调整缓冲区大小
static int major_num;
static char buffer[BUFFER_SIZE];
static DEFINE_MUTEX(lock); // 互斥锁
static int head = 0; // 读指针
static int tail = 0; // 写指针
static int buffer_full = 0; // 缓冲区是否已满
static int dev_open(struct inode *, struct file *);
static int dev_release(struct inode *, struct file *);
static ssize_t dev_read(struct file *, char *, size_t, loff_t *);
static ssize_t dev_write(struct file *, const char *, size_t, loff_t *);
static struct file_operations fops = {
.open = dev_open,
.release = dev_release,
.read = dev_read,
.write = dev_write,
};
static int __init char_dev_init(void) {
major_num = register_chrdev(0, DEVICE_NAME, &fops);
if (major_num < 0) {
printk(KERN_ALERT "Failed to register a major number\n");
return major_num;
}
printk(KERN_INFO "Registered correctly with major number %d\n", major_num);
return 0;
}
static void __exit char_dev_exit(void) {
unregister_chrdev(major_num, DEVICE_NAME);
printk(KERN_INFO "Unregistered correctly\n");
}
static int dev_open(struct inode *inodep, struct file *filep) {
printk(KERN_INFO "Device opened\n");
return 0;
}
static ssize_t dev_read(struct file *filep, char *buf, size_t count, loff_t *offset) {
int bytes_to_read, ret_val;
wait_event_interruptible(filep->f_path.dentry->d_inode->i_wait, !buffer_full);
mutex_lock(&lock);
bytes_to_read = min(tail - head, count);
if (bytes_to_read > 0) {
ret_val = copy_to_user(buf, &buffer[head], bytes_to_read);
if (ret_val == 0) {
head += bytes_to_read;
buffer_full = 0; // 缓冲区不再满
} else {
ret_val = -EFAULT;
}
} else {
ret_val = -EAGAIN; // 没有数据可读
}
mutex_unlock(&lock);
return ret_val;
}
static ssize_t dev_write(struct file *filep, const char *buf, size_t count, loff_t *offset) {
int bytes_to_write, ret_val;
wait_event_interruptible(filep->f_path.dentry->d_inode->i_wait, head != tail);
mutex_lock(&lock);
bytes_to_write = min(BUFFER_SIZE - tail, count);
ret_val = copy_from_user(&buffer[tail], buf, bytes_to_write);
if (ret_val == 0) {
tail += bytes_to_write;
buffer_full = (tail == head); // 缓冲区满
wake_up_interruptible(&filep->f_path.dentry->d_inode->i_wait); // 唤醒读进程
} else {
ret_val = -EFAULT;
}
mutex_unlock(&lock);
return ret_val ? ret_val : bytes_to_write;
}
static int dev_release(struct inode *inodep, struct file *filep) {
printk(KERN_INFO "Device successfully closed\n");
return 0;
}
module_init(char_dev_init);
module_exit(char_dev_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple character device driver with circular buffer and mutex");
LLLKLLLLL
最新推荐文章于 2024-08-04 17:35:08 发布