“简短阅读”从文件系统,什么时候可以发生? [英] "short read" from filesystem, when can it happen?

查看:101
本文介绍了“简短阅读”从文件系统,什么时候可以发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显,read(2)系统调用通常可以返回比要求读取的字节更少的字节。然而,不少程序假设在使用本地文件时,read(2)永远不会比所要求的返回更少(除非文件比较短)。

<因此,我的问题是:在Linux上,在哪些情况下可以读取(2)返回小于从打开的文件中读取并且没有遇到EOF并且读取的数量最多只有几千字节的请求?有人猜测:


  • 可以接收到的信号中断一个这样的读取,但不能它会失败?

  • 不同的文件系统会影响这种行为吗?有什么特别的关于jffs2的?


解决方案

POSIX.1-2008 states


如果
文件中剩余的字节数少于,则返回的值可能小于
如果
read()
请求被
信号中断,或者文件是管道或
FIFO或特殊文件,
的数量少于可用的字节数

读取数据。

基于文件系统通常使用不间断读取,这意味着
读取操作通常不会被信号中断。基于网络的
文件系统有时使用可中断的读取,这可以返回部分数据或无数据。
(在NFS的情况下,可以使用 intr 挂载选项进行配置。)
它们有时也会实现超时。

请记住,甚至/ some /任意/文件/路径可能指的是一个FIFO或
的特殊文件,所以你认为是一个普通的文件可能不是。因此,即使不太可能,处理部分阅读也是一个好的做法。

It is obvious that in general the read(2) system call can return less bytes than what was asked to be read. However, quite a few programs assume that when working with a local files, read(2) never returns less than what was asked (unless the file is shorter, of course).

So, my question is: on Linux, in which cases can read(2) return less than what was requested if reading from an open file and EOF is not encountered and the amount being read is a few kilobytes at maximum?

Some guesses:

  • Can received signals interrupt a read like that, but not make it fail?
  • Can different filesystems affect this behavior? Is there anything special about jffs2?

解决方案

POSIX.1-2008 states:

The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading.

Disk-based filesystems generally use uninterruptible reads, which means that the read operation generally cannot be interrupted by a signal. Network-based filesystems sometimes use interruptible reads, which can return partial data or no data. (In the case of NFS this is configurable using the intr mount option.) They sometimes also implement timeouts.

Keep in mind that even /some/arbitrary/file/path may refer to a FIFO or special file, so what you thought was a regular file may not be. It is therefore good practice to handle partial reads even though they may be unlikely.

这篇关于“简短阅读”从文件系统,什么时候可以发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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