How To Receive Output From A Child Process' ST

2019-06-10 00:08发布

问题:

I have a long-running console-based application Sender that sends simple text to STDOUT using non-buffered output such as cout << "Message" << flush(). I want to create an MFC dialog-based application (named Receiver) that starts Sender and can read it's output. Receiver should also be able to detect when Sender has died, or be able to kill Sender if it wants to. Sender knows nothing of Reciever, and I can't change Sender's code.

My first attempt was to create pipes with redirected STDIN and STDOUT for the child process and use asynchronous ReadFileEx calls to read in Sender's data. This isn't working correctly, and I've posted a separate thread about those specific problems.

My question is, how should I be doing this, in general architectural terms? I don't want Receiver's main loop to block or poll, but should use some flavor of Wait function.

回答1:

You have 2 basic options. Option 1 you've already tried, doing asynchronous (aka nonblocking) IO to read/write from the child process. Option 2 is to create a separate thread in the Receiver process that does blocking reads/writes from/to the child process.

I'd recommend option 2, I find it much easier. You then, of course, have the problem of how to get the data from the helper thread to the main thread. You'll need to use locks and maybe semaphores for that. It should be less of a hassle than nonblocking IO, however.