I'm trying to switch my brain from Node.js/Objective-C iOS programming to C++ programming, and it's a little bit taxing. Node.js and Objective-C with iOS do not have a run loop that I am supposed to manage. So please also help bend my mind to the different concepts.

I am setting up an EAGI program for Asterisk (http://www.voip-info.org/wiki/view/Asterisk+EAGI) that gets fed commands from Asterisk STDIN, sends commands back with STDOUT, and at the same time receives raw PCM audio data on FD 3 (STDERR+1).

At first, the program will be discarding all data it receives from FD 3, until it's ready for the recording. When it's ready to receive the raw audio, it will start taking the data received on FD 3, encoding it, and sending that out on a data socket.

In Node.js we could just pipe all data from fd 3 to something and that would happen "asynchronously" and not interfere with the processing of STDIN data at the same time.

When moving to C++, what is the method I should be using to read from FD 3 while being able to process STDIN and is this all done on the main run loop? And will non-blocking IO code cause the system processor to spike for the duration of the program's runtime, and should I try to use threads instead then?

有帮助吗?

解决方案

You would use some async IO library (or use the nitty gritty posix or win32 api yourself if you are masochistic) and use it to create a dispatcher loop.

For example in Boost's asio library you would create a boost::asio::io_service open the streams and start the async_read with a handler that will do what you want and call run on the io_service which will start the dispatcher loop.

其他提示

You (and node.js) cannot read from 2 streams simultaneously on a single thread. You'll have to either interleave reads as data is received, or read from both on different threads.

You could use beginthread() to start a function in a thread, and read from there. Use setbuf() to redirect the FD to a buffer in your program that you can use to read using the standard file IO routines.

... or you can just use Boost::IOStreams or Boost::asio and let the library do all the hard work for you.

许可以下: CC-BY-SA归因
scroll top