write() 系统调用何时写入所有请求的缓冲区而不是仅执行部分写入? [英] When does the write() system call write all of the requested buffer versus just doing a partial write?

查看:30
本文介绍了write() 系统调用何时写入所有请求的缓冲区而不是仅执行部分写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我指望我的 write() 系统调用来写,例如 100 个字节,我总是把 write() 调用放在一个循环中,以检查返回的长度是否是我期望发送的长度和, 如果不是,它会碰撞缓冲区指针并按写入的数量减少长度.

If I am counting on my write() system call to write say e.g., 100 bytes, I always put that write() call in a loop that checks to see if the length that gets returned is what I expected to send and, if not, it bumps the buffer pointer and decreases the length by the amount that was written.

所以我再一次这样做了,但是现在有了 StackOverflow,我可以问大家是否人们知道我的写作何时会写出我要求的所有内容,而不是给我部分写的内容?

So once again I just did this, but now that there's StackOverflow, I can ask you all if people know when my writes will write ALL that I ask for versus give me back a partial write?

附加评论:X-Istence 的回复提醒我,我应该注意到文件描述符是阻塞的(即,不是非阻塞的).我认为他建议阻塞文件描述符上的 write() 不会写入所有指定数据的唯一方法是当 write() 被信号中断时.这对我来说似乎至少具有直觉意义......

Additional comments: X-Istence's reply reminded me that I should have noted that the file descriptor was blocking (i.e., not non-blocking). I think he is suggesting that the only way a write() on a blocking file descriptor will not write all the specified data is when the write() is interrupted by a signal. This seems to make at least intuitive sense to me...

推荐答案

您需要检查 errno 以查看您的调用是否被中断,或者为什么 write() 提前返回,以及为什么它只写入了一定数量的字节.

You need to check errno to see if your call got interrupted, or why write() returned early, and why it only wrote a certain number of bytes.

来自 男人 2 写

在受流控制的套接字等对象上使用非阻塞 I/O 时,write() 和 writev() 可能写入的字节数少于请求的字节数;必须注意返回值,并在可能的情况下重试剩余的操作.

When using non-blocking I/O on objects such as sockets that are subject to flow control, write() and writev() may write fewer bytes than requested; the return value must be noted, and the remainder of the operation should be retried when possible.

基本上,除非您正在写入非阻塞套接字,否则唯一会发生这种情况的是您被信号中断.

Basically, unless you are writing to a non-blocking socket, the only other time this will happen is if you get interrupted by a signal.

[EINTR] 信号在完成之前中断了写入.

[EINTR] A signal interrupted the write before it could be completed.

请参阅 手册页 有关可以返回的内容以及何时返回的更多信息.从那里您需要确定错误是否严重到足以记录错误并退出,或者您是否可以继续手头的操作!

See the Errors section in the man page for more information on what can be returned, and when it will be returned. From there you need to figure out if the error is severe enough to log an error and quit, or if you can continue the operation at hand!

这在书中都有讨论:Advanced Unix Programming作者:Marc J. Rochkind,我在本书的帮助下编写了无数程序,并会在为类似 OS 的 UNIX 编程时推荐它.

This is all discussed in the book: Advanced Unix Programming by Marc J. Rochkind, I have written countless programs with the help of this book, and would suggest it while programming for a UNIX like OS.

这篇关于write() 系统调用何时写入所有请求的缓冲区而不是仅执行部分写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆