When recv blocks?

对着背影说爱祢 提交于 2019-12-24 05:29:10

问题


The goal is to read data from a socket without blocking. The Linux manual page says:

The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested.

Does it mean that I don't have to pass MSG_DONTWAIT flag to recv() after polling the socket descriptor with select()/poll()/epoll()?


回答1:


The behaviour of recv/read depends on the characteristics of the socket itself. If the socket is marked as non-blocking, these calls should immediately return EAGAIN/EWOULDBLOCK rather than blocking the process.

The socket can be marked as non-blocking prior to reading from it, usually via fcntl or ioctl.

What this excerpt from the manual says is that, basically, reads on both blocking and non-blocking sockets are not required to fill the whole buffer that is supplied. That is why it is important to check the result of the recv/read calls in order to know how much of the buffer contains the actual data and how much is garbage.

It is not a good idea at all to use blocking sockets in conjunction with the IO polling calls such as select/poll/epoll. Even if the polling call indicates that a particular socket is ready for reading, a blocking socket would sometimes still block.



来源:https://stackoverflow.com/questions/15136308/when-recv-blocks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!