为什么连续写入会在缓冲区中留下 4K 字节?
Why does write continuously leave 4K bytes in the buffer?
我基本上有以下代码:
int fileWrite(int file, void * pBuffer, size_t size)
{
size_t bytesWritten = (size_t)write( file, pBuffer, size ) ;
if (bytesWritten != size)
{
return -1;
}
return 0;
}
如果大小为 1GB,它可以工作,但是当大小为 ~2GB 时,它会始终保留 4K 字节。我可以通过将写入包装在一个循环中并向上移动缓冲区来解决这个问题,但我很好奇为什么它总是失败。
比如size是2147483648,write只写2147479552,剩下4096不写。为什么会发生这种情况,始终将写入包装在一个循环中是否正确?
你可以在man 2 write
中找到答案:
It is not an error if this number is smaller than the number of bytes
requested; this may happen for example because the disk device was
filled.
并且来自 write()
手册页描述:
ssize_t write(int fd, const void *buf, size_t count);
According to POSIX.1, if count
is greater than SSIZE_MAX
, the result
is implementation-defined; see NOTES for the upper limit on Linux.
NOTES
On Linux, write()
(and similar system calls) will transfer at most
0x7ffff000
(2,147,479,552) bytes, returning the number of bytes
actually transferred. (This is true on both 32-bit and 64-bit
systems.)
我基本上有以下代码:
int fileWrite(int file, void * pBuffer, size_t size)
{
size_t bytesWritten = (size_t)write( file, pBuffer, size ) ;
if (bytesWritten != size)
{
return -1;
}
return 0;
}
如果大小为 1GB,它可以工作,但是当大小为 ~2GB 时,它会始终保留 4K 字节。我可以通过将写入包装在一个循环中并向上移动缓冲区来解决这个问题,但我很好奇为什么它总是失败。
比如size是2147483648,write只写2147479552,剩下4096不写。为什么会发生这种情况,始终将写入包装在一个循环中是否正确?
你可以在man 2 write
中找到答案:
It is not an error if this number is smaller than the number of bytes requested; this may happen for example because the disk device was filled.
并且来自 write()
手册页描述:
ssize_t write(int fd, const void *buf, size_t count);
According to POSIX.1, if
count
is greater thanSSIZE_MAX
, the result is implementation-defined; see NOTES for the upper limit on Linux.NOTES
On Linux,
write()
(and similar system calls) will transfer at most0x7ffff000
(2,147,479,552) bytes, returning the number of bytes actually transferred. (This is true on both 32-bit and 64-bit systems.)