0

C# has this nice Process.OutputDataReceived() method that occurs when each time the process write a line to stdout, and for some reason I need this implementation in C++, for Windows only. I tried boost::process with async io, something like

    boost::asio::async_read(ap, boost::asio::buffer(buf),
        [&](const boost::system::error_code& ec, std::size_t size)
        {
            std::cout << buf.data() << '\n';
        });

However the callback only happens once, and won't continue if the buffer is not big enough. I want the functionality that it keeps on "monitoring" the child process until it exits.

sz ppeter
  • 1,698
  • 1
  • 9
  • 21

1 Answers1

1

Process.BeginOutputReadLine() simply starts an async task that monitors the process's stdout and fires OutputDataReceived() whenever any data is received.

In C++, that basically boils down to calling CreateProcess(), redirecting its STDOUT to a local pipe, and then you can use PeekNamedPipe() or overlapped I/O to monitor and read the pipe asynchronously, or you can just read from the pipe synchronously in a separate worker thread.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Can only make it work with anonymous pipe (thus losing async ability) but having no luck with named pipe. Can you elaborate more? – sz ppeter Nov 19 '22 at 13:10
  • [Overlapped I/O on anonymous pipe](https://stackoverflow.com/questions/60645/overlapped-i-o-on-anonymous-pipe) – Remy Lebeau Nov 19 '22 at 16:51