C - infinite read from cat in Device file

霸气de小男生 提交于 2019-12-12 04:51:57

问题


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?

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;
 }

回答1:


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

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;
}

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



来源:https://stackoverflow.com/questions/26484046/c-infinite-read-from-cat-in-device-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!