Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
SC::Process Struct Reference

Execute a child process with standard file descriptors redirection. More...

#include <Process.h>

Classes

struct  Options
 
struct  StdIn
 
struct  StdOut
 
struct  StdStream
 

Public Types

using StdErr = StdOut
 

Public Member Functions

Result waitForExitSync ()
 Waits (blocking) for process to exit after launch. It can only be called if Process::launch succeeded.
 
template<typename Out = StdOut, typename In = StdIn, typename Err = StdErr>
Result launch (Span< const StringSpan > cmd, Out &&stdOut=Out(), In &&stdIn=In(), Err &&stdErr=Err())
 Launch child process with the given arguments.
 
template<typename Out = StdOut, typename In = StdIn, typename Err = StdErr>
Result exec (Span< const StringSpan > cmd, Out &&stdOut=Out(), In &&stdIn=In(), Err &&stdErr=Err())
 Executes a child process with the given arguments, waiting (blocking) until it's fully finished.
 
int32_t getExitStatus () const
 gets the return code from the exited child process (valid only after exec or waitForExitSync)
 
Result setWorkingDirectory (StringSpan processWorkingDirectory)
 Sets the starting working directory of the process that will be launched / executed.
 
void inheritParentEnvironmentVariables (bool inherit)
 Controls if the newly spawned child process will inherit parent process environment variables.
 
Result setEnvironment (StringSpan environmentVariable, StringSpan value)
 Sets the environment variable for the newly spawned child process.
 
 Process (Span< native_char_t > commandMemory={}, Span< native_char_t > environmentMemory={})
 Constructs a Process object passing (optional) memory storage for command and environment variables.
 

Static Public Member Functions

static size_t getNumberOfProcessors ()
 Returns number of (virtual) processors available.
 
static bool isWindowsConsoleSubsystem ()
 Returns true only under Windows if executable is compiled with /SUBSYSTEM:Console
 
static bool isWindowsEmulatedProcess ()
 Returns true if we're emulating x64 on ARM64 or the inverse on Windows.
 

Public Attributes

ProcessID processID
 ID of the process (can be the same as handle on Posix)
 
Options options
 Options for the child process (hide console window etc.)
 
ProcessDescriptor::Handle handle = ProcessDescriptor::Invalid
 

Friends

struct ProcessChain
 
struct ProcessFork
 

Detailed Description

Execute a child process with standard file descriptors redirection.


Features:

  • Redirect standard in/out/err of a child process to a Pipe
  • Inherit child process file descriptors from parent process
  • Ignore (silence) child process standard file descriptor
  • Wait for the child process exit code

Example: execute child process (launch and wait for it to fully execute)

// Example: execute child process (launch and wait for it to fully execute)
SC_TRY(Process().exec({"cmd.exe", "-h"}));

Example: execute child process, redirecting stdout to a string

// Example: execute child process, redirecting stdout to a string
SmallString<256> output; // could be also just String
SC_TRY(Process().exec({"where.exe", "winver"}, output));
// Output now contains "C:\Windows\System32\winver.exe\n"

Example: launch a child process and wait for it to finish execution

// Example: launch a child process and explicitly wait for it to finish execution
Process process(commandArena.toSpan(), environmentArena.toSpan());
SC_TRY(process.launch({"ls", "-l"}));
// ...
// Here you can do I/O to and from the spawned process
// ...
SC_TRY(process.waitForExitSync());
// This is equivalent to process.exec({"ls", "-l"})

Example: execute child process, filling its stdin with a StringSpan

// Example: execute child process, filling its stdin with a StringView
// This is equivalent of shell command:
// `echo "child process" | grep process`
SC_TRY(Process().exec({"grep", "process"}, Process::StdOut::Inherit(), "child proc"));

Example: read process output using a pipe, using launch + waitForExitSync

// Example: read process output using a pipe, using launch + waitForExitSync
Process process;
PipeDescriptor outputPipe;
SC_TRY(process.launch({"executable.exe", "--argument1", "--argument2"}, outputPipe));
String output = StringEncoding::Ascii; // Could also use SmallString<N>
SC_TRY(outputPipe.readPipe.readUntilEOF(output));
SC_TRY(process.waitForExitSync());
// ... Do something with the 'output' string

Example: Add an environment variable

Process process(commandArena.toSpan(), environmentArena.toSpan());
// This child process will inherit parent environment variables plus NewEnvVar
SC_TEST_EXPECT(process.setEnvironment("NewEnvVar", "SomeValue"));
String output;
// Spawn the child process writing all env variables as KEY=VALUE\n to stdout, redirected to output
SC_TEST_EXPECT(spawnChildAndPrintEnvironmentVars(process, output));
// We can check that the NewEnvVar has been set to SomeValue
StringView out = output.view();
SC_TEST_EXPECT(out.containsString("NewEnvVar=SomeValue"));
// PATH env var exists because we are inheriting environment

Example: Redefine an environment variable

Process process(commandArena.toSpan(), environmentArena.toSpan());
// This child process will inherit parent environment variables but we re-define PATH
SC_TEST_EXPECT(process.setEnvironment("PATH", "/usr/sane_cpp_binaries"));
String output;
// Spawn the child process writing all env variables as KEY=VALUE\n to stdout, redirected to output
SC_TEST_EXPECT(spawnChildAndPrintEnvironmentVars(process, output));
// PATH env var has been re-defined
StringView out = output.view();
SC_TEST_EXPECT(out.containsString("PATH=/usr/sane_cpp_binaries"));

Example: Disable environment variable inheritance

Process process(commandArena.toSpan(), environmentArena.toSpan());
String output;
// Spawn the child process writing all env variables as KEY=VALUE\n to stdout, redirected to output
SC_TEST_EXPECT(spawnChildAndPrintEnvironmentVars(process, output));
// PATH env var doesn't exist because of Process::inheritParentEnvironmentVariables(false)
StringView out = output.view();
SC_TEST_EXPECT(not out.containsString("PATH="));

Constructor & Destructor Documentation

◆ Process()

SC::Process::Process ( Span< native_char_t > commandMemory = {},
Span< native_char_t > environmentMemory = {} )
inline

Constructs a Process object passing (optional) memory storage for command and environment variables.

Parameters
commandMemoryMemory storage for command and arguments. If empty, a default storage will be used.
environmentMemoryMemory storage for environment variables. If empty, a default storage will be used.

Member Function Documentation

◆ exec()

template<typename Out = StdOut, typename In = StdIn, typename Err = StdErr>
Result SC::Process::exec ( Span< const StringSpan > cmd,
Out && stdOut = Out(),
In && stdIn = In(),
Err && stdErr = Err() )
inline

Executes a child process with the given arguments, waiting (blocking) until it's fully finished.

Parameters
cmdProcess executable path and its arguments (if any)
stdOutProcess::StdOut::Ignore{}, Process::StdOut::Inherit{} or redirect stdout to String/Vector/Span
stdInProcess::StdIn::Ignore{}, Process::StdIn::Inherit{} or feed stdin from StringSpan/String/Vector/Span
stdErrProcess::StdErr::Ignore{}, Process::StdErr::Inherit{} or redirect stderr to String/Vector/Span
Returns
Error if the requested executable doesn't exist / is not accessible / it cannot be executed

◆ getExitStatus()

int32_t SC::Process::getExitStatus ( ) const
inline

gets the return code from the exited child process (valid only after exec or waitForExitSync)

◆ getNumberOfProcessors()

static size_t SC::Process::getNumberOfProcessors ( )
staticnodiscard

Returns number of (virtual) processors available.

◆ inheritParentEnvironmentVariables()

void SC::Process::inheritParentEnvironmentVariables ( bool inherit)
inline

Controls if the newly spawned child process will inherit parent process environment variables.

◆ isWindowsConsoleSubsystem()

static bool SC::Process::isWindowsConsoleSubsystem ( )
staticnodiscard

Returns true only under Windows if executable is compiled with /SUBSYSTEM:Console

◆ isWindowsEmulatedProcess()

static bool SC::Process::isWindowsEmulatedProcess ( )
staticnodiscard

Returns true if we're emulating x64 on ARM64 or the inverse on Windows.

◆ launch()

template<typename Out = StdOut, typename In = StdIn, typename Err = StdErr>
Result SC::Process::launch ( Span< const StringSpan > cmd,
Out && stdOut = Out(),
In && stdIn = In(),
Err && stdErr = Err() )
inline

Launch child process with the given arguments.

Parameters
cmdProcess executable path and its arguments (if any)
stdOutProcess::StdOut::Ignore{}, Process::StdOut::Inherit{} or redirect stdout to String/Vector/Span
stdInProcess::StdIn::Ignore{}, Process::StdIn::Inherit{} or feed stdin from StringSpan/String/Vector/Span
stdErrProcess::StdErr::Ignore{}, Process::StdErr::Inherit{} or redirect stderr to String/Vector/Span
Returns
Error if the requested executable doesn't exist / is not accessible / it cannot be executed

◆ setEnvironment()

Result SC::Process::setEnvironment ( StringSpan environmentVariable,
StringSpan value )

Sets the environment variable for the newly spawned child process.

◆ setWorkingDirectory()

Result SC::Process::setWorkingDirectory ( StringSpan processWorkingDirectory)

Sets the starting working directory of the process that will be launched / executed.

◆ waitForExitSync()

Result SC::Process::waitForExitSync ( )

Waits (blocking) for process to exit after launch. It can only be called if Process::launch succeeded.

Member Data Documentation

◆ options

Options SC::Process::options

Options for the child process (hide console window etc.)

◆ processID

ProcessID SC::Process::processID

ID of the process (can be the same as handle on Posix)


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