gpt4 book ai didi

c - POSIX 部分写入()

转载 作者:太空狗 更新时间:2023-10-29 11:18:25 25 4
gpt4 key购买 nike

如 SUSv4 或 POSIX.1-2008 中所述
http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html#tag_16_685_08
如果写入() 到非阻塞管道/FIFO,write() 调用可能返回小于nbytes 的值。因此,有必要在下面演示的循环中检查返回值并写入() 缓冲区的其余部分:

while (bytes_to_write > 0) {
select(...); // Or poll()
retv = write(...);
if (retv < 0)
... // Error
bytes_to_write -= retv;
}

该标准没有提及常规文件、特殊文件(又名设备)和套接字,尤其是基于流的套接字(例如 TCP 套接字和 UNIX 域套接字)。

那么,我有以下两个问题:

  • 部分write()(或部分send())是否可能发生在常规文件(或带有 O_NONBLOCK 未设置的套接字)上?
  • 非阻塞套接字上的writev() 和sendmsg() 怎么样? 这很重要,因为处理部分写入的 vector (struct iovec [])有点麻烦。

抱歉英语不好。

最佳答案

好的。由于该标准不提供任何保证,我们不能假设完整的 write()

我用 Google 搜索了部分 writev 并得到了答案:

http://developerweb.net/viewtopic.php?id=4154

Yes, I've seen that behavior before as well (though, with sendmsg() and its iovecs)... And, actually, no it's NOT incorrect/unexpected behavior... Both read()/recv() and write()/send() (and all permutations of the I/O funcs) can return short reads/writes, and all sockets code needs to be prepared to deal with that... It doesn't matter if they're blocking or non-blocking mode sockets, either... All that controls is what happens when the buffer is totally empty (in the case of input) or totally full (in the case of output)... But, when the send buffer isn't quite full, any write to it (via a blocking or non-blocking socket) of more than the amount of free space left will write as much as it can, and then return the short write count... And, you are expected to handle calling it again, to send the remaining amount... With normal write()/send(), it's easy to do, but with writev()/sendmsg() iovecs, it does become tricky to handle, and a real pain... But, you still MUST do it

writev_all() 无法避免。

谢谢。

关于c - POSIX 部分写入(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31737793/

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