[英]When do writes on a socket block?
I'm writing a network application based on an epoll loop and thread pool for handling requests. 我正在编写一个基于epoll循环和线程池的网络应用程序来处理请求。 In each thread I take special care not to block on client reads, by using non-blocking sockets and returning as soon as read returns EAGAIN (or EWOULDBLOCK to be POSIX compliant...). 在每个线程中,我都特别注意不要阻塞客户端读取,方法是使用非阻塞套接字,并在读取返回EAGAIN(或EWOULDBLOCK以兼容POSIX ...)后立即返回。
Should I take special care in socket writes too? 我在套接字写时也应该特别注意吗? I don't see myself sending enough data to fill the system TCP buffers, and blocking for a while shouldn't be too harmful. 我看不到自己发送足够的数据来填充系统TCP缓冲区,并且阻塞一段时间不会太有害。 Is this the only case where a write on a socket blocks? 这是唯一一种阻止套接字写操作的情况吗? Not enough buffer size? 缓冲区大小不足?
Also, can a socket be declared non-blocking for reads and blocking for writes? 另外,是否可以将套接字声明为非阻塞读取状态和阻塞写入状态? Or should I use fcntl all the time to switch between these behaviours? 还是我应该一直使用fcntl在这些行为之间进行切换?
Thanks! 谢谢!
The only case where a write on a socket blocks is when the data written won't fit in the buffer. 在套接字上进行写操作的唯一情况是,当写的数据不适合缓冲区时。 Ideally, you would handle writes much the way you handle reads. 理想情况下,您将以处理读取的方式处理写入。 You don't need to switch before each write. 您无需在每次写入之前进行切换。 If you want to block on write, use this logic: 如果要阻止写入,请使用以下逻辑:
Perform the write. 执行写入。
If it completes, you're done. 如果完成,就完成了。
Switch the socket to blocking. 将插座切换为阻塞状态。
Perform the (rest of) the write. 执行(其余)写操作。
Switch the socket back to non-blocking. 将套接字切换回非阻塞状态。
The correct way to handle this is to use non-blocking I/O throughout given that you're using non-blocking reads. 解决此问题的正确方法是,在使用非阻塞读取的情况下,始终使用非阻塞I / O。 When you do a write, if you get -1/EWOULDBLOCK, start selecting on that socket for writeability, and when you get it, retry the write. 进行写操作时,如果得到-1 / EWOULDBLOCK,则开始在该套接字上选择以提高可写性,并在获得该写操作时重试该写操作。 If that succeeds, stop selecting on writeability for that socket. 如果成功,请停止选择该套接字的可写性。 Don't switch to blocking-mode for that socket, it defeats the whole purpose. 不要为该套接字切换到阻塞模式,这会破坏整个目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.