Process API

This API allows you to easily launch, monitor, wait on, and terminate processes without getting into fork details.

Basic Usage

There is a configuration structure that allows you to setup how you want your process to be created. It contains the following fields:

  • arguments - a list of command line arguments (first argument is the path to the binary)
  • environment - key value pairs of environment variables
  • working_directory - the working directory to use

You can then spawn a process and wait on it, like so:

#include "ark/process/process.hh"

using namespace ark::process;

ProcessConfiguration config;
config.arguments = { "/path/to/my/binary", "-v" };

Process process(config);
process.wait();

std::cout << "Process exited with code " << process.return_code() << std::endl;

Note that you can wait for a fixed duration as well (say, wait for a few seconds, rather than until the process exits). This allows you to do maintenance work, or time out if the process is taking too long.

To kill a process, either let the process object fall out of scope, or use the kill API:

Process process(config);

if (!process.wait(std::chrono::seconds{1}))
{
    std::cout << "Process took too long, stopping it." << std::endl;
    process.kill();
}

The terminate API exists as a more aggressive version of kill. These map to their underlying POSIX signals.

Finally, you can read standard output/error from the process by using the read_output API:

Process process(config);

while (!process.wait(std::chrono::milliseconds{100}))
{
    std::cout << process.read_output(std::chrono::milliseconds{0});
}

The read_output API takes a duration in – passing a zero duration in will just check to see if something is available; otherwise it waits for that long for output to become available before returning.