cat 函数无限次调用 read() [英] cat function calling read() infinite times
问题描述
我正在研究简单的字符设备驱动程序.我在模块中实现了读写功能,问题是当我尝试使用 cat/dev/devicefile
读取设备文件时,它进入无限循环,即重复读取相同的数据.有人可以建议我解决这个问题吗?下面是我的驱动程序代码.
I am working on simple character device driver. I have implemented read and write functions in the module, the problem is when I try to read the device file using cat /dev/devicefile
it is going into infinite loop i.e. reading the same data repeatedly. Can someone suggest me any solution to this problem? Below is my driver code.
#include<linux/module.h>
#include<linux/fs.h>
#include<linux/string.h>
#include<asm/uaccess.h>
#include<linux/init.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("character device driver");
MODULE_AUTHOR("Srinivas");
static char msg[100]={0};
static int t;
static int dev_open(struct inode *, struct file *);
static int dev_rls(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 =
{
.read = dev_read,
.open = dev_open,
.write = dev_write,
.release = dev_rls,
};
static int himodule( void )
{
t = 0;
t = register_chrdev(0, "chardevdriver", &fops);
if (t < 0)
printk(KERN_ALERT"device registration failed
");
else
printk(KERN_ALERT"device registered successfully
");
printk(KERN_ALERT"major number is %d", t);
return 0;
}
static void byemodule(void)
{
unregister_chrdev(t, "chardevdriver");
printk(KERN_ALERT"successfully unregistered
");
}
static int dev_open(struct inode *inod, struct file *fil)
{
printk(KERN_ALERT"inside the dev open");
return 0;
}
static ssize_t dev_read(struct file *filp, char *buff, size_t len, loff_t *off)
{
short count = 0;
while (msg[count] != 0) {
put_user(msg[count], buff++);
count++;
}
return count;
}
static ssize_t dev_write(struct file *filp, const char *buff, size_t len, loff_t *off)
{
short count = 0;
printk(KERN_ALERT"inside write
");
memset(msg,0,100);
printk(KERN_ALERT" size of len is %zd",len);
while (len > 0) {
msg[count] = buff[count];
len--;
count++;
}
return count;
}
static int dev_rls(struct inode *inod,struct file *fil)
{
printk(KERN_ALERT"device closed
");
return 0;
}
module_init(himodule);
module_exit(byemodule);
推荐答案
.read
函数也应该正确处理它的 len
和 off
参数.实现从内存缓冲文件读取的最简单方法是使用 simple_read_from_buffer
助手:
.read
function should also correctly process its len
and off
arguments. The simplest way to implement reading from memory-buffered file is to use simple_read_from_buffer
helper:
static ssize_t dev_read(struct file *filp, char *buff, size_t len, loff_t *off)
{
return simple_read_from_buffer(buff, len, off, msg, 100);
}
您可以出于教育目的检查该助手的代码(在 fs/libfs.c
中定义).
You can inspect code of that helper (defined in fs/libfs.c
) for educational purposes.
顺便说一句,对于您的 .write
方法,您可以使用 simple_write_to_buffer
助手.
BTW, for your .write
method you could use simple_write_to_buffer
helper.
这篇关于cat 函数无限次调用 read()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!