尽管如此,请参阅 Linux select 手册页:在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() 会阻塞吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!