读取描述符的非阻塞调用 [英] Non-blocking call for reading descriptor

查看:35
本文介绍了读取描述符的非阻塞调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 fd 描述符,我可以通过调用 read(fd, buffer,...) 来读取它.现在,我想在实际拨打电话之前检查是否有任何要阅读的内容,因为电话正在阻塞.我该怎么做?

I have a fd descriptor, which I can use to read from by calling read(fd, buffer,...). Now, I want to check if there is anything to read before actually making the call, because the call is blocking. How do I do this?

推荐答案

int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);

上面的代码片段将为非阻塞访问配置这样的描述符.如果调用 read 时数据不可用,则系统调用将失败并返回 -1 并且 errno 设置为 EAGAIN.有关详细信息,请参阅 fnctl 手册页.

The code snippet above will configure such a descriptor for non-blocking access. If data is not available when you call read, then the system call will fail with a return value of -1 and errno is set to EAGAIN. See the fnctl man pages for more information.

或者,您可以使用带有可配置超时的 select 来检查和/或等待更多数据的指定时间间隔.这种方法可能正是您想要的,而且效率更高.

Alternatively, you can use select with a configurable timeout to check and/or wait a specified time interval for more data. This method is probably what you want and can be much more efficient.

这篇关于读取描述符的非阻塞调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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