cat函数调用read()无限次

我正在研究简单的字符设备驱动程序。 我在模块中实现了读写function,问题是当我尝试使用cat /dev/devicefile读取设备文件时,它会进入无限循环,即重复读取相同的数据。 有人可以建议我解决这个问题吗? 以下是我的驱动程序代码。

 #include #include #include #include #include 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) { msg[count] = buff[count]; len--; count++; } return count; } static int dev_rls(struct inode *inod,struct file *fil) { printk(KERN_ALERT"device closed\n"); return 0; } module_init(himodule); module_exit(byemodule); 

.read函数也应正确处理其lenoff参数。 从内存缓冲文件中实现读取的最简单方法是使用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定义)以用于教育目的。

顺便说一下,对于你的.write方法,你可以使用simple_write_to_buffer helper。

您不尊重传递给dev_read函数的缓冲区大小,因此您可能在cat调用未定义的行为。 试试这个:

 static ssize_t dev_read( struct file *filp, char *buff, size_t len, loff_t *off ) { size_t count = 0; printk( KERN_ALERT"inside read %d\n", *off ); while( msg[count] != 0 && count < len ) { put_user( msg[count], buff++ ); count++; } return count; } 

通过正确设置*offmy_read()第四个参数my_read()可以解决此问题。

您需要第一次返回计数,第二次返回零。

 if(*off == 0) { while (msg[count] != 0) { put_user(msg[count], buff++); count++; (*off)++; } return count; } else return 0;