在内核模块中的".read"函数中进行错误检查 [英] Error checking in a '.read' function in kernel module
问题描述
.read
操作应在内核模块字符设备中返回什么?
What should a .read
operation return in a kernel module character device?
我知道copy_to_user(...)
返回未复制的字节数,成功返回0.我看到了一些示例,这些示例使read()
函数return -EFAULT
如果copy_to_user(...)
返回除0之外的任何值.
I know that copy_to_user(...)
returns the number of bytes not copied and on success returns 0. I saw examples which make the read()
function return -EFAULT
if copy_to_user(...)
returns anything other than 0.
但是成功之后此表示返回0,而此表示返回读取的字节数.应该返回什么?
But then upon success this says to return 0 and this says to return the number of bytes read. What should be returning?
我也应该检查
static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset)
喜欢检查buffer==NULL
或len == something
?如果是这样,我应该在状况不好的情况下退货吗?
like checking if buffer==NULL
or len == something
? If so, what should I return on a bad condition?
推荐答案
.read
操作应返回以下任意一个:
.read
operation should return either:
- 复制到用户提供的缓冲区中的字节数,或
- 负错误代码
此外,操作应更新*offset
值,因此从文件中进一步读取将返回下一部分数据.
Additionally, operation should update *offset
value, so futher reading from the file will return next portion of data.
如果驱动程序实现遵循此规则,则cat
,dd
之类的标准命令将正确解释 read 系统调用的结果,并通过重复执行,将完整的内容"输出给用户".
If driver implementation follows this rules, standard commmands like cat
, dd
will interpret result of read system call correctly, and, by possibly repeating it, output to the user full "content" of the device.
通常,在copy_to_user
调用中检查buffer
参数的正确性.如果此调用失败(返回非零值),通常-c .read
返回-EFAULT.
Normally, correctness of buffer
parameter is checked in copy_to_user
call. If this call fails(returns non-zero), -EFAULT is usually returned by .read
.
len
参数很少检查错误.假设data_len
为剩余数据的长度:
len
argument is rarely checked for errors. Assuming data_len
to be length of remaing data:
-
如果
len
<data_len
,将第一个len
个字节复制到缓冲区中并返回len
if
len
<data_len
, copy firstlen
bytes into buffer and returnlen
如果len
> data_len
,请将所有剩余字节复制到缓冲区中并返回data_len
if len
> data_len
, copy all remaining bytes into buffer and return data_len
如果data_len
或len
为0,则返回0
if data_len
or len
is 0, return 0
有时设备的数据只能按预定义大小的部分读取.在这种情况下,可以检查len
并返回-EINVAL,以防其值不合适.也可以检查buffer
是否对齐.
Sometimes device's data can be read only by portions of predefined size. In that situation you can check len
and return -EINVAL in case it has inappropriate value. buffer
can also being checked for alignment.
例如,如果.read
成功返回0,则它是正确的,直到设备被自己编写的用户空间程序使用为止,该程序不检查返回数据的实际长度.
As for example, where .read
returns 0 on success, it is correct until device is used by own-written user-space program, which doesn't check actual length of returning data.
这篇关于在内核模块中的".read"函数中进行错误检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!