C - infinite read from cat in Device file

2019-08-31 09:22发布

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条回答
疯言疯语
2楼-- · 2019-08-31 09:42

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.

查看更多
登录 后发表回答