gpt4 book ai didi

linux写(): does it try to write as many bytes as possible?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:51 24 4
gpt4 key购买 nike

如果我以这种方式使用 write:write (fd, buf, 10000000/* 10MB */) 其中 fd 是一个套接字并使用阻塞 I/O,内核是否会尝试刷新尽可能多的字节以便仅调用一次就足够了?或者我必须根据它的返回值多次调用write?如果发生这种情况,是否意味着 fd 有问题?

==============================编辑================ ================

谢谢大家的回答。此外,如果我将 fd 放入 poll 并且它以 POLLOUT 成功返回,那么无法阻止对 write 的调用并写入所有数据,除非 fd 出现问题?

最佳答案

在阻塞模式下,write(2)只有写入指定数量的字节才会返回。如果它不能写入,它会等待。

在非阻塞(O_NONBLOCK)模式下它不会等待。它会立即返回。如果它可以写入所有这些,那么它将是成功的,否则它将相应地设置 errno。然后你检查了 errno 如果它的 EWOULDBLOCKEAGAIN 你必须调用相同的 write agian。

来自 write(2) 的手册

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).)

是的,fd 可能有问题。

还要注意这点

A successful return from write() does not make any guarantee that data has been committed to disk. In fact, on some buggy implementations, it does not even guar‐ antee that space has successfully been reserved for the data. The only way to be sure is to call fsync(2) after you are done writing all your data.

关于linux写(): does it try to write as many bytes as possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14032888/

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