Full standard stream redirection without potential deadlock

  c++, io-redirection, linux

If I want to redirect stdin, stdout, and stderr, without the risk of deadlock (for example, child process may need more data on stdin to flush stdout), do I have to spawn multiple threads, or is there any other solution to the problem. Current implementation:

std::thread stderr_proc{read, io_redirector.handle(), stderr, io_redirector.stderr()};
std::thread stdout_proc{read, io_redirector.handle(), stdout, io_redirector.stdout()};
write(io_redirector.handle(), stdin, io_redirector.stdin());

int status;
if(::waitpid(pid, &status, 0) == -1) { abort(); }

stdout_proc.join();
stderr_proc.join();

Including the main thread, this implementation uses one thread per stream to avoid deadlock, but I think it is quite heavy-weight to start two new threads. Especially since this is called from one of many worker threads, it would be nice to have a single-threaded solution.

Source: Windows Questions C++

LEAVE A COMMENT