问题描述
根据read(2)的手册页,仅当到达EOF时它才返回零。
According to the man page for read(2), it only returns zero when EOF is reached.
但是,这似乎是不正确的,有时可能返回零,也许是因为文件还没有准备好被读取?在从磁盘读取文件之前,我应该调用select()以查看其是否准备就绪吗?
However, It appears this is incorrect and that it may sometimes return zero, perhaps because the file is not ready to be read yet? Should I call select() to see if it is ready before reading a file from disk?
请注意,nBytes为:1,445,888
Note that nBytes is: 1,445,888
一些示例代码:
fd_set readFdSet;
timeval timeOutTv;
timeOutTv.tv_sec = 0;
timeOutTv.tv_usec = 0;
// Let's see if we'll block on the read.
FD_ZERO(&readFdSet);
FD_SET(fd, &readFdSet);
int selectReturn = ::select(fd + 1, &readFdSet, NULL, NULL, &timeOutTv);
if (selectReturn == 0) {
// There is still more to read.
return false; // But return early.
} else if (selectReturn < 0) {
clog << "Error: select failure: " << strerror(errno) << endl;
abort();
} else {
assert(FD_ISSET(fd, &readFdSet));
try {
const int bufferSizeAvailable = _bufferSize - _availableIn;
if (_availableIn) {
assert(_availableIn <= _bufferSize);
memmove(_buffer, _buffer + bufferSizeAvailable, _availableIn);
}
ssize_t got = ::read(fd, _buffer + _availableIn, bufferSizeAvailable);
clog << " available: " << bufferSizeAvailable << " availableIn: "
<< _availableIn << " bufferSize: " << _bufferSize << " got "
<< got << endl;
return got == 0;
} catch (Err &err) {
err.append("During load from file.");
throw;
}
}
输出读取(当失败且没有数据读取时) ):
The output reads (when it fails with no data read):
available: 1445888 availableIn: 0 bufferSize: 1445888 got: 0
这是使用VMware Server 1.0.10在32位centos4上作为虚拟机运行的。读取的文件系统是虚拟机本地的。主机是Windows Server 2008 32位。
This is running on centos4 32 bit as a virtual machine using VMware Server 1.0.10. The file system being read is local to the virtual machine. The host machine is windows server 2008 32 bit.
uname -a表示:
The uname -a says:
Linux q-centos4x32 2.6.9-89.0.25.ELsmp #1 SMP Thu May 6 12:28:03 EDT 2010 i686 i686 i386 GNU/Linux
我注意到链接给出以下状态:
I notice that the link http://opengroup.org/onlinepubs/007908775/xsh/read.html given below 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...
If a read() is interrupted by a signal before it reads any data, it will return -1 with errno set to [EINTR].
If a read() is interrupted by a signal after it has successfully read some data, it will return the number of bytes read.
所以,也许我收到中断读取的信号,因此由于以下两种情况而返回的值为零是错误还是认为已读取零字节?
So, perhaps I am getting a signal interrupting the read and thus the value returned is zero because of either a bug or it thinks zero bytes were read?
推荐答案
知道了!我有一个未初始化的内存读取(UMR),并且错误地寻找到文件的结尾。
Figured it out! I had an Uninitialized Memory Read (UMR) and was incorrectly seeking to the end of the file.
这篇关于当不在EOF时,read(2)可以返回零吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!