VLink  2.0.0
A high-performance communication middleware
vlink::Process Class Reference

Owns and drives a single child process with asynchronous I/O reporting. More...

#include <process.h>

Collaboration diagram for vlink::Process:

Public Types

enum  State : uint8_t { kNotRunningState = 0 , kStartingState = 1 , kRunningState = 2 }
 Coarse lifecycle stage of the child process. More...
 
enum  ExitStatus : uint8_t { kNormalExitStatus = 0 , kCrashExitStatus = 1 }
 How the most recent child exited. More...
 
enum  Error : uint8_t {
  kNoError = 0 , kUnknownError = 1 , kStartError = 2 , kCrashedError = 3 ,
  kTimedOutError = 4 , kWriteError = 5 , kReadError = 6 , kBufferOverflowError = 7
}
 Sticky error indicator set by failing operations. More...
 
enum  Mode : uint8_t {
  kSeparateMode = 0 , kMergedMode = 1 , kForwardedMode = 2 , kForwardedOutputMode = 3 ,
  kForwardedErrorMode = 4
}
 Routing of the child's stdout/stderr file descriptors. More...
 
using EnvironmentMap = std::unordered_map< std::string, std::string >
 Map type used to pass environment overrides to set_environment(). More...
 
using ErrorCallback = Function< void(Error)>
 Callback signature invoked when the Error state changes. More...
 
using FinishedCallback = Function< void(int, ExitStatus)>
 Callback signature invoked when the child exits. More...
 
using ReadyReadCallback = Function< void()>
 Callback signature invoked whenever new data is available on a pipe. More...
 
using StateChangedCallback = Function< void(State)>
 Callback signature invoked when the process State transitions. More...
 

Public Member Functions

 Process ()
 Constructs an idle process driver with no child attached. More...
 
 ~Process ()
 Destructor. Terminates the child if still alive then frees driver resources. More...
 
 Process (Process &&other) noexcept=delete
 
Processoperator= (Process &&other) noexcept=delete
 
State get_state () const
 Returns the lifecycle state of the currently attached child. More...
 
Error get_error () const
 Returns the most recently latched error code. More...
 
int get_exit_code () const
 Returns the exit code of the most recent child process. More...
 
ExitStatus get_exit_status () const
 Returns how the most recent child terminated. More...
 
bool is_running () const
 Reports whether the attached child is currently running. More...
 
int64_t get_process_id () const
 Returns the OS-level identifier of the child process. More...
 
void set_max_buffer_size (size_t size)
 Limits the in-memory capture buffer used for stdout/stderr. More...
 
size_t get_max_buffer_size () const
 Returns the configured capture-buffer limit. More...
 
void set_environment (const EnvironmentMap &env_map)
 Defines the environment that will be applied at the next start() call. More...
 
EnvironmentMap get_environment () const
 Returns the currently configured environment override. More...
 
void set_process_mode (Mode mode)
 Sets the I/O channel routing that will be applied at the next start() call. More...
 
Mode get_process_mode () const
 Returns the currently configured I/O routing mode. More...
 
void set_inherit_environment (bool inherit)
 Controls whether the child inherits the parent environment in addition to the override map. More...
 
bool get_inherit_environment () const
 Reports whether the child currently inherits the parent environment. More...
 
void set_working_directory (const std::string &dir)
 Sets the working directory used at the next start() call. More...
 
std::string get_working_directory () const
 Returns the currently configured working directory. More...
 
void register_error_callback (ErrorCallback &&callback)
 Installs a callback fired when the Error state changes. More...
 
void register_finished_callback (FinishedCallback &&callback)
 Installs a callback fired when the child exits. More...
 
void register_ready_read_stdout_callback (ReadyReadCallback &&callback)
 Installs a callback fired when stdout has new data buffered. More...
 
void register_ready_read_stderr_callback (ReadyReadCallback &&callback)
 Installs a callback fired when stderr has new data buffered. More...
 
void register_state_changed_callback (StateChangedCallback &&callback)
 Installs a callback fired on every State transition. More...
 
void start (const std::string &program, const std::vector< std::string > &arguments={})
 Launches program with the given argument vector. More...
 
void start_command (const std::string &command)
 Parses a shell-style command line and launches it. More...
 
bool wait_for_started (int msecs=kDefaultWaitTimeoutMs)
 Blocks until the child leaves kStartingState or the timeout elapses. More...
 
bool wait_for_finished (int msecs=kDefaultWaitTimeoutMs)
 Blocks until the child terminates or the timeout elapses. More...
 
bool wait_for_ready_read (int msecs=kDefaultWaitTimeoutMs)
 Blocks until new pipe data becomes available or the timeout elapses. More...
 
void terminate ()
 Requests cooperative termination of the child. More...
 
void kill ()
 Forces immediate termination of the child via SIGKILL / TerminateProcess. More...
 
void close (bool force_kill_on_timeout=false)
 Sends SIGTERM and optionally escalates to kill() after the wait timeout. More...
 
size_t bytes_available_stdout () const
 Returns the number of buffered bytes available to read from stdout. More...
 
size_t bytes_available_stderr () const
 Returns the number of buffered bytes available to read from stderr. More...
 
bool can_read_line_stdout () const
 Reports whether a newline-terminated line is fully buffered on stdout. More...
 
bool can_read_line_stderr () const
 Reports whether a newline-terminated line is fully buffered on stderr. More...
 
bool read_line_stdout (std::string &line)
 Reads one buffered line from stdout. More...
 
bool read_line_stderr (std::string &line)
 Reads one buffered line from stderr. More...
 
size_t read_stdout (std::vector< uint8_t > &buffer, size_t max_size)
 Reads up to max_size bytes of buffered stdout into buffer. More...
 
size_t read_stderr (std::vector< uint8_t > &buffer, size_t max_size)
 Reads up to max_size bytes of buffered stderr into buffer. More...
 
bool read_all_output (std::vector< uint8_t > &buffer)
 Drains all buffered stdout into buffer. More...
 
bool read_all_error (std::vector< uint8_t > &buffer)
 Drains all buffered stderr into buffer. More...
 
bool read_all (std::vector< uint8_t > &buffer)
 Drains all buffered stdout and stderr into buffer. More...
 
bool read_all_output (std::string &str)
 Drains all buffered stdout into str. More...
 
bool read_all_error (std::string &str)
 Drains all buffered stderr into str. More...
 
bool read_all (std::string &str)
 Drains all buffered stdout and stderr into str. More...
 
size_t write (const std::vector< uint8_t > &buffer, int timeout_ms=kDefaultWriteTimeoutMs)
 Writes a byte buffer to the child's stdin. More...
 
size_t write (const std::string &str, int timeout_ms=kDefaultWriteTimeoutMs)
 Writes a string to the child's stdin. More...
 
void close_write_channel ()
 Closes the stdin pipe, signalling EOF to the child. More...
 

Static Public Member Functions

static int execute (const std::string &program, const std::vector< std::string > &arguments={}, int timeout_ms=kDefaultExecuteTimeoutMs)
 Synchronously executes a program and returns its exit code. More...
 
static bool start_detached (const std::string &program, const std::vector< std::string > &arguments={})
 Launches a program detached from the calling process and returns immediately. More...
 

Static Public Attributes

static constexpr int kInfinite {-1}
 Sentinel value used to request an unbounded wait. More...
 
static constexpr int kDefaultWaitTimeoutMs {3000}
 Default deadline for wait_for_started / wait_for_finished (3000 ms). More...
 
static constexpr int kDefaultWriteTimeoutMs {5000}
 Default deadline for blocking writes to the child's stdin (5000 ms). More...
 
static constexpr int kDefaultExecuteTimeoutMs {30000}
 Default deadline for the synchronous execute() helper (30000 ms). More...
 
static constexpr int kDestructorWaitTimeoutMs {5000}
 Grace period the destructor allows after sending SIGTERM before escalating. More...
 

Detailed Description

Owns and drives a single child process with asynchronous I/O reporting.

The instance is non-copyable and non-movable. A new child may only be launched after any previous one has terminated and the internal state has been cleaned up.

Member Typedef Documentation

◆ EnvironmentMap

using vlink::Process::EnvironmentMap = std::unordered_map<std::string, std::string>

Map type used to pass environment overrides to set_environment().

◆ ErrorCallback

Callback signature invoked when the Error state changes.

◆ FinishedCallback

Callback signature invoked when the child exits.

The first parameter is the exit code; the second is kNormalExitStatus or kCrashExitStatus.

◆ ReadyReadCallback

Callback signature invoked whenever new data is available on a pipe.

◆ StateChangedCallback

Callback signature invoked when the process State transitions.

Member Enumeration Documentation

◆ Error

enum vlink::Process::Error : uint8_t

Sticky error indicator set by failing operations.

Enumerator
kNoError 

No error has been observed.

kUnknownError 

Catch-all bucket for unmapped errors.

kStartError 

Failed to launch the requested program.

kCrashedError 

Child process crashed.

kTimedOutError 

A blocking wait expired before its condition was met.

kWriteError 

Writing to the child's stdin failed.

kReadError 

Reading from a captured pipe failed.

kBufferOverflowError 

Captured output exceeded set_max_buffer_size.

◆ ExitStatus

How the most recent child exited.

Enumerator
kNormalExitStatus 

Child returned from main or called exit normally.

kCrashExitStatus 

Child was terminated by a signal or crashed.

◆ Mode

enum vlink::Process::Mode : uint8_t

Routing of the child's stdout/stderr file descriptors.

Enumerator
kSeparateMode 

Capture stdout and stderr through independent pipes.

kMergedMode 

Capture stdout; merge stderr into the stdout pipe.

kForwardedMode 

Inherit parent stdout/stderr without capture.

kForwardedOutputMode 

Inherit stdout; capture stderr.

kForwardedErrorMode 

Capture stdout; inherit stderr.

◆ State

enum vlink::Process::State : uint8_t

Coarse lifecycle stage of the child process.

Enumerator
kNotRunningState 

No child is currently active.

kStartingState 

start() has been called and the OS is launching the binary.

kRunningState 

Child has been successfully launched and is executing.

Constructor & Destructor Documentation

◆ Process() [1/2]

vlink::Process::Process ( )

Constructs an idle process driver with no child attached.

◆ ~Process()

vlink::Process::~Process ( )

Destructor. Terminates the child if still alive then frees driver resources.

The sequence sends SIGTERM via terminate(), drains any pending pipe data, waits up to kDestructorWaitTimeoutMs for a graceful exit, then escalates to SIGKILL via kill() and waits up to a further 1000 ms before releasing the I/O thread, pipes and child handles.

◆ Process() [2/2]

vlink::Process::Process ( Process &&  other)
deletenoexcept

Member Function Documentation

◆ bytes_available_stderr()

size_t vlink::Process::bytes_available_stderr ( ) const

Returns the number of buffered bytes available to read from stderr.

Returns
Bytes available on stderr.

◆ bytes_available_stdout()

size_t vlink::Process::bytes_available_stdout ( ) const

Returns the number of buffered bytes available to read from stdout.

Returns
Bytes available on stdout.

◆ can_read_line_stderr()

bool vlink::Process::can_read_line_stderr ( ) const

Reports whether a newline-terminated line is fully buffered on stderr.

Returns
true when read_line_stderr() will deliver a complete line.

◆ can_read_line_stdout()

bool vlink::Process::can_read_line_stdout ( ) const

Reports whether a newline-terminated line is fully buffered on stdout.

Returns
true when read_line_stdout() will deliver a complete line.

◆ close()

void vlink::Process::close ( bool  force_kill_on_timeout = false)

Sends SIGTERM and optionally escalates to kill() after the wait timeout.

Parameters
force_kill_on_timeoutWhen true and the child has not exited within kDefaultWaitTimeoutMs, kill() is invoked. On Windows terminate() is already forceful so the flag is effectively ignored. Default: false.

◆ close_write_channel()

void vlink::Process::close_write_channel ( )

Closes the stdin pipe, signalling EOF to the child.

◆ execute()

static int vlink::Process::execute ( const std::string &  program,
const std::vector< std::string > &  arguments = {},
int  timeout_ms = kDefaultExecuteTimeoutMs 
)
static

Synchronously executes a program and returns its exit code.

Standard output and standard error are discarded. Returns -1 when the launch fails or the timeout elapses.

Parameters
programPath to the executable.
argumentsArgument vector. Default: empty.
timeout_msMaximum wait in milliseconds. Default: kDefaultExecuteTimeoutMs.
Returns
Exit code on success, or -1 on failure.

◆ get_environment()

EnvironmentMap vlink::Process::get_environment ( ) const

Returns the currently configured environment override.

Returns
Environment variable map.

◆ get_error()

Error vlink::Process::get_error ( ) const

Returns the most recently latched error code.

Returns
Sticky Error value; kNoError if no error has occurred.

◆ get_exit_code()

int vlink::Process::get_exit_code ( ) const

Returns the exit code of the most recent child process.

Only meaningful once get_state() reports kNotRunningState.

Returns
Exit code passed to exit() or implied by signal termination.

◆ get_exit_status()

ExitStatus vlink::Process::get_exit_status ( ) const

Returns how the most recent child terminated.

Returns
kNormalExitStatus on graceful exit, kCrashExitStatus on signal/crash.

◆ get_inherit_environment()

bool vlink::Process::get_inherit_environment ( ) const

Reports whether the child currently inherits the parent environment.

Returns
true when the parent environment is merged.

◆ get_max_buffer_size()

size_t vlink::Process::get_max_buffer_size ( ) const

Returns the configured capture-buffer limit.

Returns
Buffer size in bytes; default is 16 MiB.

◆ get_process_id()

int64_t vlink::Process::get_process_id ( ) const

Returns the OS-level identifier of the child process.

Returns
Process ID, or -1 when no child is attached.

◆ get_process_mode()

Mode vlink::Process::get_process_mode ( ) const

Returns the currently configured I/O routing mode.

Returns
Current Mode.

◆ get_state()

State vlink::Process::get_state ( ) const

Returns the lifecycle state of the currently attached child.

Returns
Current State value.

◆ get_working_directory()

std::string vlink::Process::get_working_directory ( ) const

Returns the currently configured working directory.

Returns
Working directory path.

◆ is_running()

bool vlink::Process::is_running ( ) const

Reports whether the attached child is currently running.

Returns
true when get_state() equals kRunningState.

◆ kill()

void vlink::Process::kill ( )

Forces immediate termination of the child via SIGKILL / TerminateProcess.

◆ operator=()

Process& vlink::Process::operator= ( Process &&  other)
deletenoexcept

◆ read_all() [1/2]

bool vlink::Process::read_all ( std::string &  str)

Drains all buffered stdout and stderr into str.

Parameters
strDestination string; replaced.
Returns
true when any data was copied.

◆ read_all() [2/2]

bool vlink::Process::read_all ( std::vector< uint8_t > &  buffer)

Drains all buffered stdout and stderr into buffer.

Parameters
bufferDestination byte vector; replaced.
Returns
true when any data was copied.

◆ read_all_error() [1/2]

bool vlink::Process::read_all_error ( std::string &  str)

Drains all buffered stderr into str.

Parameters
strDestination string; replaced.
Returns
true when any data was copied.

◆ read_all_error() [2/2]

bool vlink::Process::read_all_error ( std::vector< uint8_t > &  buffer)

Drains all buffered stderr into buffer.

Parameters
bufferDestination byte vector; replaced.
Returns
true when any data was copied.

◆ read_all_output() [1/2]

bool vlink::Process::read_all_output ( std::string &  str)

Drains all buffered stdout into str.

Parameters
strDestination string; replaced.
Returns
true when any data was copied.

◆ read_all_output() [2/2]

bool vlink::Process::read_all_output ( std::vector< uint8_t > &  buffer)

Drains all buffered stdout into buffer.

Parameters
bufferDestination byte vector; replaced.
Returns
true when any data was copied.

◆ read_line_stderr()

bool vlink::Process::read_line_stderr ( std::string &  line)

Reads one buffered line from stderr.

Parameters
lineDestination string; receives buffered data including a trailing newline when one was buffered.
Returns
true when at least one byte was copied into line.

◆ read_line_stdout()

bool vlink::Process::read_line_stdout ( std::string &  line)

Reads one buffered line from stdout.

Parameters
lineDestination string; receives buffered data including a trailing newline when one was buffered.
Returns
true when at least one byte was copied into line.

◆ read_stderr()

size_t vlink::Process::read_stderr ( std::vector< uint8_t > &  buffer,
size_t  max_size 
)

Reads up to max_size bytes of buffered stderr into buffer.

Parameters
bufferDestination byte vector.
max_sizeUpper bound on bytes to copy.
Returns
Number of bytes actually copied.

◆ read_stdout()

size_t vlink::Process::read_stdout ( std::vector< uint8_t > &  buffer,
size_t  max_size 
)

Reads up to max_size bytes of buffered stdout into buffer.

Parameters
bufferDestination byte vector.
max_sizeUpper bound on bytes to copy.
Returns
Number of bytes actually copied.

◆ register_error_callback()

void vlink::Process::register_error_callback ( ErrorCallback &&  callback)

Installs a callback fired when the Error state changes.

Parameters
callbackCallback invoked from the monitor thread.

◆ register_finished_callback()

void vlink::Process::register_finished_callback ( FinishedCallback &&  callback)

Installs a callback fired when the child exits.

Parameters
callbackCallback invoked with exit code and exit status.

◆ register_ready_read_stderr_callback()

void vlink::Process::register_ready_read_stderr_callback ( ReadyReadCallback &&  callback)

Installs a callback fired when stderr has new data buffered.

Parameters
callbackCallback invoked from the monitor thread.

◆ register_ready_read_stdout_callback()

void vlink::Process::register_ready_read_stdout_callback ( ReadyReadCallback &&  callback)

Installs a callback fired when stdout has new data buffered.

Parameters
callbackCallback invoked from the monitor thread.

◆ register_state_changed_callback()

void vlink::Process::register_state_changed_callback ( StateChangedCallback &&  callback)

Installs a callback fired on every State transition.

Parameters
callbackCallback invoked from the monitor thread with the new State.

◆ set_environment()

void vlink::Process::set_environment ( const EnvironmentMap env_map)

Defines the environment that will be applied at the next start() call.

Parameters
env_mapVariable map to merge into or replace the parent environment based on the set_inherit_environment() setting.

◆ set_inherit_environment()

void vlink::Process::set_inherit_environment ( bool  inherit)

Controls whether the child inherits the parent environment in addition to the override map.

Parameters
inherittrue to merge with the parent environment, false to use only the override map.

◆ set_max_buffer_size()

void vlink::Process::set_max_buffer_size ( size_t  size)

Limits the in-memory capture buffer used for stdout/stderr.

When the captured output exceeds size bytes the kBufferOverflowError code is latched. Passing 0 restores the default of 16 MiB.

Parameters
sizeNew buffer limit in bytes.

◆ set_process_mode()

void vlink::Process::set_process_mode ( Mode  mode)

Sets the I/O channel routing that will be applied at the next start() call.

Parameters
modeRouting mode for stdout/stderr.

◆ set_working_directory()

void vlink::Process::set_working_directory ( const std::string &  dir)

Sets the working directory used at the next start() call.

Parameters
dirAbsolute path the child should chdir to before executing the program.

◆ start()

void vlink::Process::start ( const std::string &  program,
const std::vector< std::string > &  arguments = {} 
)

Launches program with the given argument vector.

Returns once the launch attempt has either succeeded (state becomes kRunningState) or failed (an Error is latched). I/O monitoring continues asynchronously on the internal monitor thread.

Parameters
programPath to the executable.
argumentsArgument vector excluding argv[0].

◆ start_command()

void vlink::Process::start_command ( const std::string &  command)

Parses a shell-style command line and launches it.

Splits command on whitespace with quote and backslash handling, then delegates to start().

Parameters
commandShell-style command string.

◆ start_detached()

static bool vlink::Process::start_detached ( const std::string &  program,
const std::vector< std::string > &  arguments = {} 
)
static

Launches a program detached from the calling process and returns immediately.

Parameters
programPath to the executable.
argumentsArgument vector. Default: empty.
Returns
true when the OS reports a successful launch.

◆ terminate()

void vlink::Process::terminate ( )

Requests cooperative termination of the child.

POSIX sends SIGTERM, which the child may catch. Windows uses TerminateProcess, which is unconditional. kill() must be used for a forced exit on POSIX.

◆ wait_for_finished()

bool vlink::Process::wait_for_finished ( int  msecs = kDefaultWaitTimeoutMs)

Blocks until the child terminates or the timeout elapses.

Parameters
msecsMaximum wait in milliseconds. Default: kDefaultWaitTimeoutMs.
Returns
true when the child has exited within the timeout.

◆ wait_for_ready_read()

bool vlink::Process::wait_for_ready_read ( int  msecs = kDefaultWaitTimeoutMs)

Blocks until new pipe data becomes available or the timeout elapses.

Parameters
msecsMaximum wait in milliseconds. Default: kDefaultWaitTimeoutMs.
Returns
true when data is now available on stdout or stderr.

◆ wait_for_started()

bool vlink::Process::wait_for_started ( int  msecs = kDefaultWaitTimeoutMs)

Blocks until the child leaves kStartingState or the timeout elapses.

A child that already exited still counts as started.

Parameters
msecsMaximum wait in milliseconds. Default: kDefaultWaitTimeoutMs.
Returns
true if the child started (even if since exited); false on launch failure, timeout, or if never started.

◆ write() [1/2]

size_t vlink::Process::write ( const std::string &  str,
int  timeout_ms = kDefaultWriteTimeoutMs 
)

Writes a string to the child's stdin.

Parameters
strString to write.
timeout_msMaximum wait in milliseconds. Default: kDefaultWriteTimeoutMs.
Returns
Number of bytes actually written.

◆ write() [2/2]

size_t vlink::Process::write ( const std::vector< uint8_t > &  buffer,
int  timeout_ms = kDefaultWriteTimeoutMs 
)

Writes a byte buffer to the child's stdin.

Parameters
bufferBytes to write.
timeout_msMaximum wait in milliseconds. Default: kDefaultWriteTimeoutMs.
Returns
Number of bytes actually written.

Member Data Documentation

◆ kDefaultExecuteTimeoutMs

constexpr int vlink::Process::kDefaultExecuteTimeoutMs {30000}
staticconstexpr

Default deadline for the synchronous execute() helper (30000 ms).

◆ kDefaultWaitTimeoutMs

constexpr int vlink::Process::kDefaultWaitTimeoutMs {3000}
staticconstexpr

Default deadline for wait_for_started / wait_for_finished (3000 ms).

◆ kDefaultWriteTimeoutMs

constexpr int vlink::Process::kDefaultWriteTimeoutMs {5000}
staticconstexpr

Default deadline for blocking writes to the child's stdin (5000 ms).

◆ kDestructorWaitTimeoutMs

constexpr int vlink::Process::kDestructorWaitTimeoutMs {5000}
staticconstexpr

Grace period the destructor allows after sending SIGTERM before escalating.

◆ kInfinite

constexpr int vlink::Process::kInfinite {-1}
staticconstexpr

Sentinel value used to request an unbounded wait.


The documentation for this class was generated from the following file: