c语言 - 无法在字符设备驱动程序中实现 write() 和 read()



我正试图创建一个简单的字符设备LKM,但我已经被困了好几天,试图让我的读写正常工作。目前,当我做这样的事情时:

echo hi > /dev/simple_character_device 

我可以看到我写的字节数是正确的。

但是,当我试图找出该设备的内容时,它会不断循环hi,直到到达一个坏地址。目前,我正在努力跟踪我在全局计数器中写入的字节数。但这似乎不对。如有任何关于实现读写的帮助,我们将不胜感激。

#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/string.h>
MODULE_LICENSE("GPL");
#define BUFFER 1024
char * buffer_data;
// Count open and closed
size_t current_count;
int my_open(struct inode *, struct file *);
int my_release(struct inode *, struct file *);
ssize_t my_read(struct file *, char __user *, size_t count, loff_t *);
ssize_t my_write(struct file *, const char __user *, size_t count, loff_t *offp); 
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = my_open,
.release = my_release,
.read = my_read,
.write = my_write
};

int reg_init(void)
{
// Allocate memory to store information 
buffer_data = kmalloc(BUFFER, GFP_KERNEL);  // Use Kernel Flag
register_chrdev(240, "simple_character_device", &fops);

printk(KERN_ALERT "Init Allocating Memory");
return 0;
}
void reg_exit(void)
{
// Free and unregister device and data
kfree(buffer_data);
unregister_chrdev(240, "simple_character_device");
printk(KERN_ALERT "Deregister Simple Character Device");
}

int my_open(struct inode *inode, struct file *file){
printk(KERN_ALERT "Open File Device.n");
return 0;
}
int my_release(struct inode *inode, struct file *file){
printk(KERN_ALERT "Close File Device.n");
return 0;
}
ssize_t my_read(struct file *filp, char __user *buff, size_t count, loff_t *offp){
// Check if we are reading within the Buffer Size
if(BUFFER - *offp < 0){
printk(KERN_ALERT "Out of buffer range.n");
return -EFAULT;
}

// Check if we fail to copy to user
if (copy_to_user(buff, buffer_data, current_count) != 0){
printk(KERN_ALERT "Failed to send character to usern");
return -EFAULT;
}
(*offp) += current_count;
printk(KERN_ALERT "Read %zu bytes.n", current_count);
return current_count;
}
ssize_t my_write(struct file *filp, const char __user *buff, size_t count, loff_t *offp){
// We need to get data FROM the user space

// Make sure we are reading within the buffer
if (*offp >= BUFFER || BUFFER - count < *offp){
printk(KERN_ALERT "ATTEMPTING TO WRITE TO OUSIDE OF BUFFER!n");
return EFAULT;
}

// Get the amount of bytes from the user
copy_from_user(buffer_data + *offp, buff, count);
*offp += count;
printk(KERN_ALERT "Wrote %zu to the device.n", count);
current_count = count;
return current_count;
}

module_init(reg_init);
module_exit(reg_exit);

在my_read((中,您不能允许在current_count之后读取缓冲区(在初始化数据结束的点之后(。如果请求的计数更远,则必须首先修剪通过的计数。如果结果计数为<=0,或者如果偏移量在current_count之后,则必须返回0以指示文件结束。

此外,您必须返回修剪后的计数(它实际上是复制给用户的(。

我希望你用echo和cat进行测试。但是,如果您使用自己的代码进行测试,按照顺序读取和写入,请不要忘记在读取和写入之间使用lseek((重置偏移量。

据我所知,您的代码看起来是一个良好的开端,但计数和文件位置管理需要一些清理。

最新更新