我正在编写一个围绕通用文件操作的包装器,并且不知道如何处理当 write 返回较小的写入大小时提供的情况。
write 的手册页说:
The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler after having written less than count bytes. (See also pipe(7).)
根据我对上述内容的理解,这是错误(中满)和激励返回(调用中断)的混合体。如果我的文件描述符都是非阻塞的,我不应该得到中断情况,那么唯一的原因就是错误。我说得对吗?
代码示例:
int size_written = write(fd, str, count);
if (size_written == -1) {
if (errno == EAGAIN) {
// poll on fd and come back later
} else {
// throw an error
}
} else if (size_written < count) {
// ***************
// what should I do here ?
// throw an error ?
// ***************
}
最佳答案
您需要在循环中使用原始 I/O 函数:
ssize_t todo = count;
for (ssize_t n; todo > 0; )
{
n = write(fd, str, todo);
if (n == -1 && errno != EINTR)
{
// error
break;
}
str += n;
todo -= n;
}
if (todo != 0) { /* error */ }
有关EINTR
的特殊条件允许写调用被信号中断,而不会导致整个操作失败。否则,我们希望最终能够写入所有数据。
如果由于文件描述符是非阻塞的并且目前无法接受任何数据而无法完成所有数据的写入,则必须存储剩余的数据,并在文件描述符发出信号表明已准备好时重试再写一次。
关于c++ - write 返回较小尺寸时该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21614150/