gpt4 book ai didi

c++ - read(2) 不在 EOF 时可以返回零吗?

转载 作者:IT王子 更新时间:2023-10-29 00:20:16 25 4
gpt4 key购买 nike

根据 read(2) 的手册页,它仅在到达 EOF 时返回零。

但是,这似乎是不正确的,它有时可能会返回零,可能是因为文件还没有准备好被读取?在从磁盘读取文件之前,我是否应该调用 select() 来查看它是否准备就绪?

注意 nBytes 是: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;
}
}

输出读取(当它因未读取数据而失败时):

available: 1445888 availableIn: 0 bufferSize: 1445888 got: 0

这是在 centos4 32 位上作为使用 VMware Server 1.0.10 的虚拟机运行的。正在读取的文件系统是虚拟机的本地文件系统。主机是windows server 2008 32位。

uname -a 说:

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

我注意到链接http://opengroup.org/onlinepubs/007908775/xsh/read.html给出以下状态:

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.

所以,也许我收到一个中断读取的信号,因此返回的值是零,因为错误或它认为读取了零字节?

最佳答案

经过一些研究,实际上在某些情况下它会返回 0,您可能不会认为这是“EOF”。

有关详细信息,请参阅 read() 的 POSIX 定义:http://opengroup.org/onlinepubs/007908775/xsh/read.html

一些值得注意的是,如果你要求它读取 0 个字节——仔细检查你是否不小心将 0 传递给它——并读取文件的“写入”部分的末尾(你实际上可以寻找超过文件末尾,如果你在那里写,它会用零“扩展”文件,但在你这样做之前,“EOF”仍然在已写部分的末尾。

我最好的猜测是您在某个地方遇到了计时问题。您需要问的一些问题是“这些文件是如何写入的?”和“当我尝试阅读它们时,我确定它们不是零长度吗?”。对于第二个,您可以在读取文件之前尝试在文件上运行 stat() 以查看其当前大小。

关于c++ - read(2) 不在 EOF 时可以返回零吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3074202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com