VLink 2.0.0
A high-performance communication middleware
Loading...
Searching...
No Matches
vlink::Process Class Reference

Cross-platform child process with async I/O and state notification. More...

#include <process.h>

Collaboration diagram for vlink::Process:

Public Types

enum  State : uint8_t { kNotRunningState = 0 , kStartingState = 1 , kRunningState = 2 }
 Lifecycle state of the child process. More...
enum  ExitStatus : uint8_t { kNormalExitStatus = 0 , kCrashExitStatus = 1 }
 How the child process exited. More...
enum  Error : uint8_t {
  kNoError = 0 , kUnknownError = 1 , kStartError = 2 , kCrashedError = 3 ,
  kTimedOutError = 4 , kWriteError = 5 , kReadError = 6 , kBufferOverflowError = 7
}
 Error codes set on failure. More...
enum  Mode : uint8_t {
  kSeparateMode = 0 , kMergedMode = 1 , kForwardedMode = 2 , kForwardedOutputMode = 3 ,
  kForwardedErrorMode = 4
}
 I/O channel routing mode. More...
using EnvironmentMap = std::unordered_map<std::string, std::string>
 Environment variable map type for set_environment().
using ErrorCallback = std::function<void(Error)>
 Callback type invoked when an error occurs.
using FinishedCallback = std::function<void(int, ExitStatus)>
 Callback type invoked when the process exits.
using ReadyReadCallback = std::function<void()>
 Callback type invoked when new data is available on a pipe.
using StateChangedCallback = std::function<void(State)>
 Callback type invoked when the process state changes.

Public Member Functions

 Process ()
 Constructs a Process object. No child is started yet.
 ~Process ()
 Destructor. Closes the process and waits up to kDestructorWaitTimeoutMs.
 Process (Process &&other) noexcept=delete
Processoperator= (Process &&other) noexcept=delete
State get_state () const
 Returns the current state of the child process.
Error get_error () const
 Returns the last error code.
int get_exit_code () const
 Returns the exit code of the child process.
ExitStatus get_exit_status () const
 Returns how the child process exited.
bool is_running () const
 Returns true if the child process is currently running.
int64_t get_process_id () const
 Returns the operating-system process ID of the child.
void set_max_buffer_size (size_t size)
 Sets the maximum buffer size for stdout and stderr capture.
size_t get_max_buffer_size () const
 Returns the configured maximum buffer size.
void set_environment (const EnvironmentMap &env_map)
 Sets the environment variables for the child process.
EnvironmentMap get_environment () const
 Returns the configured environment map.
void set_process_mode (Mode mode)
 Sets the I/O channel routing mode.
Mode get_process_mode () const
 Returns the configured I/O channel mode.
void set_inherit_environment (bool inherit)
 Controls whether the child inherits the parent's environment.
bool get_inherit_environment () const
 Returns whether the child inherits the parent environment.
void set_working_directory (const std::string &dir)
 Sets the working directory for the child process.
std::string get_working_directory () const
 Returns the configured working directory.
void register_error_callback (ErrorCallback &&callback)
 Registers a callback for error events.
void register_finished_callback (FinishedCallback &&callback)
 Registers a callback invoked when the child exits.
void register_ready_read_stdout_callback (ReadyReadCallback &&callback)
 Registers a callback invoked when new stdout data is available.
void register_ready_read_stderr_callback (ReadyReadCallback &&callback)
 Registers a callback invoked when new stderr data is available.
void register_state_changed_callback (StateChangedCallback &&callback)
 Registers a callback invoked when the process state changes.
void start (const std::string &program, const std::vector< std::string > &arguments={})
 Launches the child process.
void start_command (const std::string &command)
 Parses and launches a shell command string.
bool wait_for_started (int msecs=kDefaultWaitTimeoutMs)
 Blocks until the child process enters kRunningState.
bool wait_for_finished (int msecs=kDefaultWaitTimeoutMs)
 Blocks until the child process exits.
bool wait_for_ready_read (int msecs=kDefaultWaitTimeoutMs)
 Blocks until new data is available on any pipe.
void terminate ()
 Requests child termination.
void kill ()
 Forcefully kills the child process (SIGKILL / TerminateProcess).
void close (bool force_kill_on_timeout=false)
 Calls terminate() and optionally force-kills after a timeout.
size_t bytes_available_stdout () const
 Returns the number of bytes available to read from stdout.
size_t bytes_available_stderr () const
 Returns the number of bytes available to read from stderr.
bool can_read_line_stdout () const
 Returns true if a complete newline-terminated line is available on stdout.
bool can_read_line_stderr () const
 Returns true if a complete newline-terminated line is available on stderr.
bool read_line_stdout (std::string &line)
 Reads one line from stdout into line.
bool read_line_stderr (std::string &line)
 Reads one line from stderr into line.
size_t read_stdout (std::vector< uint8_t > &buffer, size_t max_size)
 Reads up to max_size bytes from stdout into buffer.
size_t read_stderr (std::vector< uint8_t > &buffer, size_t max_size)
 Reads up to max_size bytes from stderr into buffer.
bool read_all_output (std::vector< uint8_t > &buffer)
 Reads all available stdout data into buffer (byte vector overload).
bool read_all_error (std::vector< uint8_t > &buffer)
 Reads all available stderr data into buffer (byte vector overload).
bool read_all (std::vector< uint8_t > &buffer)
 Reads all available stdout and stderr data into buffer (byte vector overload).
bool read_all_output (std::string &str)
 Reads all available stdout data into str.
bool read_all_error (std::string &str)
 Reads all available stderr data into str.
bool read_all (std::string &str)
 Reads all available stdout and stderr data into str.
size_t write (const std::vector< uint8_t > &buffer, int timeout_ms=kDefaultWriteTimeoutMs)
 Writes buffer to the child's stdin.
size_t write (const std::string &str, int timeout_ms=kDefaultWriteTimeoutMs)
 Writes a string to the child's stdin.
void close_write_channel ()
 Closes the write channel (stdin pipe), signalling EOF to the child.

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 waits for it to finish.
static bool start_detached (const std::string &program, const std::vector< std::string > &arguments={})
 Starts a program in the background and returns immediately.

Static Public Attributes

static constexpr int kInfinite {-1}
 Sentinel wait timeout meaning wait indefinitely.
static constexpr int kDefaultWaitTimeoutMs {3000}
 Default timeout for wait_for_started() and wait_for_finished() in milliseconds.
static constexpr int kDefaultWriteTimeoutMs {5000}
 Default timeout for write() in milliseconds.
static constexpr int kDefaultExecuteTimeoutMs {30000}
 Default timeout for the synchronous execute() helper in milliseconds.
static constexpr int kDestructorWaitTimeoutMs {5000}
 Time the destructor waits for the child to exit before force-killing in milliseconds.

Detailed Description

Cross-platform child process with async I/O and state notification.

A single Process object manages one child process at a time. It is non-copyable and non-moveable.

Member Typedef Documentation

◆ EnvironmentMap

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

Environment variable map type for set_environment().

◆ ErrorCallback

using vlink::Process::ErrorCallback = std::function<void(Error)>

Callback type invoked when an error occurs.

◆ FinishedCallback

using vlink::Process::FinishedCallback = std::function<void(int, ExitStatus)>

Callback type invoked when the process exits.

First argument is the exit code; second is kNormalExitStatus or kCrashExitStatus.

◆ ReadyReadCallback

using vlink::Process::ReadyReadCallback = std::function<void()>

Callback type invoked when new data is available on a pipe.

◆ StateChangedCallback

using vlink::Process::StateChangedCallback = std::function<void(State)>

Callback type invoked when the process state changes.

Member Enumeration Documentation

◆ Error

enum vlink::Process::Error : uint8_t

Error codes set on failure.

Enumerator
kNoError 

No error.

kUnknownError 

Unknown error.

kStartError 

Failed to start the process (e.g., file not found).

kCrashedError 

Process crashed.

kTimedOutError 

A wait operation timed out.

kWriteError 

Write to stdin failed.

kReadError 

Read from stdout/stderr failed.

kBufferOverflowError 

Output exceeded max_buffer_size.

◆ ExitStatus

How the child process exited.

Enumerator
kNormalExitStatus 

Exited normally (via exit() or return from main).

kCrashExitStatus 

Killed by a signal or crashed.

◆ Mode

enum vlink::Process::Mode : uint8_t

I/O channel routing mode.

Enumerator
kSeparateMode 

stdout and stderr buffered as separate pipes

kMergedMode 

stderr merged into stdout pipe

kForwardedMode 

Both stdout and stderr forwarded to the parent process.

kForwardedOutputMode 

stdout forwarded; stderr buffered separately

kForwardedErrorMode 

stderr forwarded; stdout buffered separately

◆ State

enum vlink::Process::State : uint8_t

Lifecycle state of the child process.

Enumerator
kNotRunningState 

Not started or has exited.

kStartingState 

start() called; waiting for exec to complete

kRunningState 

Successfully running.

Constructor & Destructor Documentation

◆ Process() [1/2]

vlink::Process::Process ( )

Constructs a Process object. No child is started yet.

Here is the caller graph for this function:

◆ ~Process()

vlink::Process::~Process ( )

Destructor. Closes the process and waits up to kDestructorWaitTimeoutMs.

◆ Process() [2/2]

vlink::Process::Process ( Process && other)
deletenoexcept
Here is the call graph for this function:

Member Function Documentation

◆ bytes_available_stderr()

size_t vlink::Process::bytes_available_stderr ( ) const
nodiscard

Returns the number of bytes available to read from stderr.

Returns
Bytes available in the stderr buffer.

◆ bytes_available_stdout()

size_t vlink::Process::bytes_available_stdout ( ) const
nodiscard

Returns the number of bytes available to read from stdout.

Returns
Bytes available in the stdout buffer.

◆ can_read_line_stderr()

bool vlink::Process::can_read_line_stderr ( ) const
nodiscard

Returns true if a complete newline-terminated line is available on stderr.

Returns
true if at least one line can be read.

◆ can_read_line_stdout()

bool vlink::Process::can_read_line_stdout ( ) const
nodiscard

Returns true if a complete newline-terminated line is available on stdout.

Returns
true if at least one line can be read.

◆ close()

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

Calls terminate() and optionally force-kills after a timeout.

Parameters
force_kill_on_timeoutIf true, calls kill() if the process has not exited after kDestructorWaitTimeoutMs. If false and the child does not exit in time, the process remains running. On Windows, terminate() is already forceful. Default: false.

◆ close_write_channel()

void vlink::Process::close_write_channel ( )

Closes the write channel (stdin pipe), signalling EOF to the child.

◆ execute()

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

Synchronously executes a program and waits for it to finish.

Blocks until the program exits or timeout_ms elapses. Returns the exit code. Stdout and stderr are discarded.

Parameters
programPath to the executable.
argumentsCommand-line arguments. Default: empty.
timeout_msMaximum wait time. Default: kDefaultExecuteTimeoutMs (30 s).
Returns
Exit code, or -1 on timeout or start failure.

◆ get_environment()

EnvironmentMap vlink::Process::get_environment ( ) const
nodiscard

Returns the configured environment map.

Returns
Environment variable map.

◆ get_error()

Error vlink::Process::get_error ( ) const
nodiscard

Returns the last error code.

Returns
kNoError if no error has occurred.

◆ get_exit_code()

int vlink::Process::get_exit_code ( ) const
nodiscard

Returns the exit code of the child process.

Valid only after get_state() returns kNotRunningState.

Returns
Exit code.

◆ get_exit_status()

ExitStatus vlink::Process::get_exit_status ( ) const
nodiscard

Returns how the child process exited.

Returns
kNormalExitStatus or kCrashExitStatus.

◆ get_inherit_environment()

bool vlink::Process::get_inherit_environment ( ) const
nodiscard

Returns whether the child inherits the parent environment.

Returns
true if inheriting.

◆ get_max_buffer_size()

size_t vlink::Process::get_max_buffer_size ( ) const
nodiscard

Returns the configured maximum buffer size.

Returns
Buffer size in bytes. Default is 16 MB (16 * 1024 * 1024).

◆ get_process_id()

int64_t vlink::Process::get_process_id ( ) const
nodiscard

Returns the operating-system process ID of the child.

Returns
PID, or -1 if not running.

◆ get_process_mode()

Mode vlink::Process::get_process_mode ( ) const
nodiscard

Returns the configured I/O channel mode.

Returns
Current mode.

◆ get_state()

State vlink::Process::get_state ( ) const
nodiscard

Returns the current state of the child process.

Returns
Current State value.

◆ get_working_directory()

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

Returns the configured working directory.

Returns
Working directory path.

◆ is_running()

bool vlink::Process::is_running ( ) const
nodiscard

Returns true if the child process is currently running.

Returns
true if state is kRunningState.

◆ kill()

void vlink::Process::kill ( )

Forcefully kills the child process (SIGKILL / TerminateProcess).

◆ operator=()

Process & vlink::Process::operator= ( Process && other)
deletenoexcept
Here is the call graph for this function:

◆ read_all() [1/2]

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

Reads all available stdout and stderr data into str.

Parameters
strDestination string.
Returns
true if any data was available.

◆ read_all() [2/2]

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

Reads all available stdout and stderr data into buffer (byte vector overload).

Parameters
bufferDestination vector; existing content is replaced.
Returns
true if any data was available.

◆ read_all_error() [1/2]

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

Reads all available stderr data into str.

Parameters
strDestination string.
Returns
true if any data was available.

◆ read_all_error() [2/2]

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

Reads all available stderr data into buffer (byte vector overload).

Parameters
bufferDestination vector; existing content is replaced.
Returns
true if any data was available.

◆ read_all_output() [1/2]

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

Reads all available stdout data into str.

Parameters
strDestination string.
Returns
true if any data was available.

◆ read_all_output() [2/2]

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

Reads all available stdout data into buffer (byte vector overload).

Parameters
bufferDestination vector; existing content is replaced.
Returns
true if any data was available.

◆ read_line_stderr()

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

Reads one line from stderr into line.

Parameters
lineOutput string. Includes the trailing newline when one is buffered.
Returns
true if a line was read.

◆ read_line_stdout()

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

Reads one line from stdout into line.

Parameters
lineOutput string. Includes the trailing newline when one is buffered.
Returns
true if a line was read.

◆ read_stderr()

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

Reads up to max_size bytes from stderr into buffer.

Parameters
bufferDestination vector.
max_sizeMaximum bytes to read.
Returns
Number of bytes actually read.

◆ read_stdout()

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

Reads up to max_size bytes from stdout into buffer.

Parameters
bufferDestination vector.
max_sizeMaximum bytes to read.
Returns
Number of bytes actually read.

◆ register_error_callback()

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

Registers a callback for error events.

Parameters
callbackInvoked with the Error code when an error occurs.

◆ register_finished_callback()

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

Registers a callback invoked when the child exits.

Parameters
callbackInvoked with (exit_code, exit_status).

◆ register_ready_read_stderr_callback()

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

Registers a callback invoked when new stderr data is available.

Parameters
callbackInvoked from the monitor thread when stderr has data.

◆ register_ready_read_stdout_callback()

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

Registers a callback invoked when new stdout data is available.

Parameters
callbackInvoked from the monitor thread when stdout has data.

◆ register_state_changed_callback()

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

Registers a callback invoked when the process state changes.

Parameters
callbackInvoked with the new State value.

◆ set_environment()

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

Sets the environment variables for the child process.

Replaces (or supplements, depending on set_inherit_environment) the child's environment with env_map.

Parameters
env_mapMap of variable name to value.

◆ set_inherit_environment()

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

Controls whether the child inherits the parent's environment.

Parameters
inheritIf true, the child inherits all parent environment variables. If false, only the variables in the EnvironmentMap are set.

◆ set_max_buffer_size()

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

Sets the maximum buffer size for stdout and stderr capture.

If the child produces more output than size bytes, kBufferOverflowError is set. Passing 0 resets the limit to the default (16 MB).

Parameters
sizeMaximum buffer size in bytes.

◆ set_process_mode()

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

Sets the I/O channel routing mode.

Parameters
modeChannel mode. Must be set before start().

◆ set_working_directory()

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

Sets the working directory for the child process.

Parameters
dirAbsolute path to the working directory.

◆ start()

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

Launches the child process.

The child is started asynchronously. Call wait_for_started() to block until the child is in kRunningState.

Parameters
programPath to the executable.
argumentsCommand-line arguments. Default: empty.

◆ start_command()

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

Parses and launches a shell command string.

Splits command by whitespace into a program and argument list, then calls start().

Parameters
commandShell command string.

◆ start_detached()

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

Starts a program in the background and returns immediately.

The started process is completely detached from the calling process. No handle is returned; the process runs until it exits on its own.

Parameters
programPath to the executable.
argumentsCommand-line arguments. Default: empty.
Returns
true if the process was successfully started.

◆ terminate()

void vlink::Process::terminate ( )

Requests child termination.

On POSIX this sends SIGTERM, which the child may handle or ignore. On Windows this uses TerminateProcess, so termination is immediate. Use kill() for an explicit forceful stop.

◆ wait_for_finished()

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

Blocks until the child process exits.

Parameters
msecsTimeout in milliseconds. Default: kDefaultWaitTimeoutMs (3000 ms).
Returns
true if the process exited within the timeout.

◆ wait_for_ready_read()

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

Blocks until new data is available on any pipe.

Parameters
msecsTimeout in milliseconds. Default: kDefaultWaitTimeoutMs (3000 ms).
Returns
true if data became available within the timeout.

◆ wait_for_started()

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

Blocks until the child process enters kRunningState.

Parameters
msecsTimeout in milliseconds. Default: kDefaultWaitTimeoutMs (3000 ms).
Returns
true if the process is running within the timeout.

◆ 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 time to wait. 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 buffer to the child's stdin.

Parameters
bufferData to write.
timeout_msMaximum time to wait for the write to complete. Default: kDefaultWriteTimeoutMs.
Returns
Number of bytes actually written.

Member Data Documentation

◆ kDefaultExecuteTimeoutMs

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

Default timeout for the synchronous execute() helper in milliseconds.

◆ kDefaultWaitTimeoutMs

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

Default timeout for wait_for_started() and wait_for_finished() in milliseconds.

◆ kDefaultWriteTimeoutMs

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

Default timeout for write() in milliseconds.

◆ kDestructorWaitTimeoutMs

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

Time the destructor waits for the child to exit before force-killing in milliseconds.

◆ kInfinite

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

Sentinel wait timeout meaning wait indefinitely.


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