[Home]BoostProcess/Examples

BOOST WIKI | BoostProcess | RecentChanges | Preferences | Page List | Links List

Boost.Process code examples

The following examples are based on some preliminary code I've written.

Binary and arguments configuration

Let's start by creating a new child process and setting it up. We simply set the binary to use and the arguments to pass to it. Note that this does not start the process.

child c;

c.set_executable("/bin/ls");
c.append_argument("/");
c.append_argument("/bin");

Stream manipulation

Now we do what'd be the most common steps to capture the output of a program. Just create a stream to read from stdout and merge everything sent to stderr into stdout.

boost::weak_ptr< child::istream > isptr(c.redirect_output(child::stdout_fileno));
c.redirect_output(child::stderr_fileno, child::stdout_fileno);

Execution

Everything is ready, so we can launch the process and start processing its output. To do the latter, we only need to read from the input stream we constructed previously:

c.start();
{
    char line[255];
    boost::shared_ptr< child::istream > is = isptr.lock();
    while (is->good()) {
        is->getline(line, 255);
        std::cout << "LINE: " << line << std::endl;
    }
}

Termination

At last, wait for the process termination (in fact, we did this before by waiting until the stream became invalid) and interpret its exit status:

status s = c.wait();

if (not s.exited() or s.exit_status() != status::exit_success)
    std::cout << "Child process exited unexpectedly" << std::endl;

BOOST WIKI | BoostProcess | RecentChanges | Preferences | Page List | Links List
Edit text of this page | View other revisions
Last edited February 27, 2005 11:20 am (diff)
Search:
Disclaimer: This site not officially maintained by Boost Developers