尽管如此,请参见Linux 选择手册页: 在Linux下,select()可能会报告 套接字文件描述符为准备用于 阅读",尽管如此 随后的读取块.这可能 例如,当数据具有 到达但经检查有误 校验和并被丢弃.也许有 在其他情况下,文件 描述符被虚假地报告为 准备好.因此使用起来可能更安全 不应在套接字上使用O_NONBLOCK 阻止.I'm reading a stream of data through TCP/IP socket. The stream load is very uneven. Sometimes large bulks of data arrive every second, sometimes no data come for an hour. In the case of long inactivity period (no data from remote server, but connection is still online) my program should take some actions.I'm implementing a timeout using a select(). It tells me if there are data ready, but I don't know exactly how much can I read without causing read() to block. Blocking is unacceptable as it may last far longer than the timeout I need.For the sake of efficiency, stream is read into large buffer and read() call is provided with that buffer size.Will read() block after select() if the buffer to be filled is greater than amount of data available right now in the socket? 解决方案 Actually it should not block (that is what select() is for!), but in fact, it might, exceptionally. Normally, read() should return up to the maximum number of bytes that you've specified, which possibly includes zero bytes (this is actually a valid thing to happen!), but it should never block after previously having reported readiness.Nevertheless, see the Linux select man page: Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on sockets that should not block. 这篇关于select()之后read()会阻塞吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 11:18
查看更多