Get stdout of a shell command using boost process
Asked Answered
A

1

4

I am trying to implement a function in C++ that runs a shell command and returns the exit code, stdout and stderr. I am using the Boost process library

std::vector<std::string> read_outline(std::string & file)
{
    bp::ipstream is; //reading pipe-stream
    bp::child c(bp::search_path("nm"), file, bp::std_out > is);

    std::vector<std::string> data;
    std::string line;

    while (c.running() && std::getline(is, line) && !line.empty())
        data.push_back(line);

    c.wait();

    return data;
}

In the above example from boost's website, in the while loop the condition c.running() is checked. What if the process finishes executing before the while loop is reached? In that case I won't be able to store the child process's stdout to data. Boost's documentation also mentions the following

[Warning] Warning The pipe will cause a deadlock if you try to read after nm exited

Hence it seems that the check for c.running() should be there in the while loop.

How do I get the stdout (and stderr) from the processes that finish running before the program reaches the while loop?

Araceli answered 25/9, 2018 at 10:54 Comment(4)
Use async mode? And BTW the warning makes no sense, since the process can still exit between the check and the getline call.Grados
How robust does your processing need to be? The solution will be different for a short-lived shell utility that will write only a small amount of data that can be easily buffered compared to a long-lived child process that's going to write large amounts of data to both stdout and stderr.Mavilia
@AndrewHenle This is going to be part of a utility that has to be very robust.Araceli
This is probably relevant, then: #45207506 Note that saving the data the child process outputs to memory can be a problem if that child process writes a lot of data to stderr or stdout.Mavilia
I
0

I believe that whats the wait call is there for. The child process isn't actually gone in whatever OS before that (it merely changes state after it's not in running state).

Indiscreet answered 25/9, 2018 at 11:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.