在 select() 之后 read() 会阻塞吗? [英] Will read() ever block after select()?

查看:55
本文介绍了在 select() 之后 read() 会阻塞吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 TCP/IP 套接字读取数据流.流负载非常不均匀.有时每秒都有大量数据到达,有时一个小时内没有数据.在长时间不活动的情况下(没有来自远程服务器的数据,但连接仍然在线)我的程序应该采取一些行动.

我正在使用 select() 实现超时.它告诉我是否有数据准备好,但我不知道在不导致 read() 阻塞的情况下我可以读取多少.阻塞是不可接受的,因为它可能持续比我需要的超时时间长得多.

为了效率起见,流被读入大缓冲区,并且 read() 调用提供了该缓冲区大小.

如果要填充的缓冲区大于套接字中当前可用的数据量,read() 会在 select() 之后阻塞吗?

解决方案

实际上它不应该阻塞(这就是 select() 的作用!),但实际上它可能,例外.通常, read() 应该返回您指定的最大字节数,其中可能包括零字节(这实际上是一个有效的事情!),但它不应该在之前报告就绪后阻塞.

尽管如此,请参阅 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() 会阻塞吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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