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

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

问题描述

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

我正在使用select()实现超时.它告诉我是否已经准备好数据,但是我不知道在不引起read()阻塞的情况下我可以读取多少数据.阻止是无法接受的,因为它的持续时间可能远远超过我需要的超时时间.

出于效率考虑,将流读入大缓冲区,并以该缓冲区大小提供read()调用.

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

解决方案

实际上,它不应该阻塞(这就是select()的目的!),但实际上,它可能可能.通常,read()最多应返回您指定的最大字节数,其中可能包括零字节(这实际上是一件有效的事情!),但在先前报告准备就绪后,它绝不应阻塞.

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

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