在内核模块中的".read"函数中进行错误检查 [英] Error checking in a '.read' function in kernel module

查看:112
本文介绍了在内核模块中的".read"函数中进行错误检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.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==NULLlen == 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.

如果驱动程序实现遵循此规则,则catdd之类的标准命令将正确解释 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 first len bytes into buffer and return len

如果len> data_len,请将所有剩余字节复制到缓冲区中并返回data_len

if len > data_len, copy all remaining bytes into buffer and return data_len

如果data_lenlen为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屋!

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