简体   繁体   English

如何在 C++ 中异步读取 ifstream?

[英]How do you read from a ifstream asynchronously in C++?

The ifstream is reading from a UNIX pipe, currently the communication is done by sending a signal to the reading application, but I would like to get rid of the signals and use proper async io. ifstream 正在从 UNIX pipe 读取,目前通信是通过向读取应用程序发送信号来完成的,但我想摆脱信号并使用正确的异步 ZF98ED07A4D5F50F47DE1410D905FZF。

In C I would use the select() function with a timeout, so I could react immediately when there is something to read, and waith for IO otherwise.在 C 中,我会使用 select() function 超时,所以当有要读取的内容时我可以立即做出反应,否则等待 IO。

In C++ I can't access the fd of the file, so I can't use select().在 C++ 中无法访问文件的 fd,因此无法使用 select()。 What's the most reasonable approach to doing this?这样做最合理的方法是什么? Do I have to use some sort of Boost library, or can this be done using the standard C++ libraries?我必须使用某种 Boost 库,还是可以使用标准 C++ 库来完成?

std::ifstream does not support asynchronous operations, it is designed for synchronous IO. std::ifstream不支持异步操作,它是为同步 IO 设计的。 You could build async IO around it using additional threads and IO queue, but in general this is not a good idea for efficiency reasons.您可以使用额外的线程和 IO 队列围绕它构建异步 IO,但总的来说,出于效率原因,这不是一个好主意。

For asynchronous IO you might want to look at Boost.ASIO , in particular its stream_descriptor , which can be used to adopt arbitrary stream file descriptors like pipes.对于异步 IO 您可能需要查看Boost.ASIO ,尤其是它的stream_descriptor ,它可用于采用任意 stream 文件描述符,如管道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM