C-从设备文件中的cat无限读取 [英] C - infinite read from cat in Device file

查看:378
本文介绍了C-从设备文件中的cat无限读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直对从cat进行无限读取感到头疼(cat无法关闭,因为它没有从我的read函数接收函数的结尾。如何实现end的读取,以便使用cat读取文件

I've been having some headache with infinite reads from cat (cat doesn’t close because it doesn’t receive end of function from my read function. How can I implement an end of read so that reading the file with cat will only produce 1 output per command in the terminal?

函数,这是我编写的内核read()函数:

function. This is the kernel read() function I've written:

static ssize_t dev_read(struct file *file, char *buf, size_t count, loff_t *ppos)
{
char tmp_buf[MAX_BUF_SIZE]; //defined as 100
int bLen=0;
sprintf(tmp_buf, "Some message");
bLen = strlen(tmp_buf);

if(copy_to_user(buf,tmp_buf, bLen)){
     return -EFAULT;
}

 return bLen;
 }


推荐答案

我正在回答,因为我是在搜索的早期发现的。

I'm answering because I found this early on in my search.

Cat持续读取直到得到一个空的响应。一旦它完成获取一些数据,它就会返回并询问还有其他东西吗? r模块说是,然后再次发送数据。您需要打破束缚,让它发送空响应。最好的方法是放置

Cat continually reads until it gets an empty response. Once it finished getting some data it goes back and asks "have anything else?" To which your module says yes and sends it the data again. You need to break the chain and have it send an empty response. The best way to do this would be to place

if(*ppos > 0){
    return 0;
}

在函数开头,并添加要发送的数据的长度退出前返回* ppos。

at the beginning of the function and add the length of the data you are sending back to *ppos before exiting.

这篇关于C-从设备文件中的cat无限读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆