5#include "../File/File.h"
6#include "../Foundation/AlignedStorage.h"
7#include "../Foundation/Internal/IGrowableBuffer.h"
8#include "../Foundation/StringPath.h"
12struct SC_COMPILER_EXPORT ProcessChain;
14using ProcessDescriptor = FileDescriptor;
81 GrowableBuffer<T>& gbuf = growableBufferStorage.reinterpret_as<GrowableBuffer<T>>();
82 placementNew(gbuf, destination);
83 growableBuffer = &gbuf;
84 operation = Operation::GrowableBuffer;
90 growableBuffer->~IGrowableBuffer();
97 operation = Operation::FileDescriptor;
98 (void)file.get(fileDescriptor, Result::Error(
"Invalid redirection file descriptor"));
104 operation = Operation::ExternalPipe;
105 pipeDescriptor = &pipe;
108 StdStream(
const StdStream&) =
delete;
109 StdStream(StdStream&&) =
delete;
110 StdStream& operator=(
const StdStream&) =
delete;
111 StdStream& operator=(StdStream&&) =
delete;
133 Operation operation = Operation::Inherit;
138 IGrowableBuffer* growableBuffer =
nullptr;
141 FileDescriptor::Handle fileDescriptor;
161 using StdStream::StdStream;
166 using StdErr = StdOut;
177 template <
int N>
StdIn(
const char (&item)[N]) :
StdIn(
StringSpan({item, N - 1},
true, StringEncoding::Ascii)) {}
185 using StdStream::StdStream;
206 const StdIn& stdIn = StdIn::Inherit{},
207 const StdErr& stdErr = StdErr::Inherit{})
209 SC_TRY(formatArguments(cmd));
210 return launch(stdOut, stdIn, stdErr);
222 const StdIn& stdIn = StdIn::Inherit{},
223 const StdErr& stdErr = StdErr::Inherit{})
225 SC_TRY(launch(cmd, stdOut, stdIn, stdErr));
226 return waitForExitSync();
254 : command({commandMemory}), environment({environmentMemory})
256 if (commandMemory.empty())
257 command = {commandStorage};
258 if (environmentMemory.empty())
259 environment = {environmentStorage};
263 ProcessExitStatus exitStatus;
265 FileDescriptor stdInFd;
266 FileDescriptor stdOutFd;
267 FileDescriptor stdErrFd;
269 Result launch(
const StdOut& stdOutput,
const StdIn& stdInput,
const StdErr& stdError);
271 Result formatArguments(Span<const StringSpan> cmd);
273 StringPath currentDirectory;
280 StringSpan::NativeWritable command;
281#if !SC_PLATFORM_WINDOWS
282 static constexpr size_t MAX_NUM_ARGUMENTS = 64;
283 size_t commandArgumentsByteOffset[MAX_NUM_ARGUMENTS];
284 size_t commandArgumentsNumber = 0;
288 StringSpan::NativeWritable environment;
290 static constexpr size_t MAX_NUM_ENVIRONMENT = 256;
292 size_t environmentByteOffset[MAX_NUM_ENVIRONMENT];
293 size_t environmentNumber = 0;
295 bool inheritEnv =
true;
297 friend struct ProcessChain;
298 ProcessChain* parent =
nullptr;
300 Process* next =
nullptr;
301 Process* prev =
nullptr;
303 friend struct ProcessFork;
304 Result launchImplementation();
337 const Process::StdErr& stdErr = Process::StdErr::Inherit{});
347 const Process::StdErr& stdErr = Process::StdErr::Inherit{})
349 SC_TRY(launch(stdOut, stdIn, stdErr));
350 return waitForExitSync();
355 struct ProcessLinkedList
357 Process* back =
nullptr;
358 Process* front =
nullptr;
360 [[nodiscard]]
bool isEmpty()
const {
return front ==
nullptr; }
363 void queueBack(Process& process);
365 ProcessLinkedList processes;
383 [[nodiscard]]
size_t size()
const {
return numberOfEnvironment; }
398 size_t numberOfEnvironment = 0;
399#if SC_PLATFORM_WINDOWS
400 static constexpr size_t MAX_ENVIRONMENTS = 256;
403 wchar_t* environment =
nullptr;
405 char** environment =
nullptr;
475 Side side = ForkParent;
476#if SC_PLATFORM_WINDOWS
477 ProcessDescriptor::Handle processHandle = ProcessDescriptor::Invalid;
478 ProcessDescriptor::Handle threadHandle = ProcessDescriptor::Invalid;
int int32_t
Platform independent (4) bytes signed int.
Definition PrimitiveTypes.h:46
char native_char_t
The native char for the platform (wchar_t (4 bytes) on Windows, char (1 byte) everywhere else )
Definition PrimitiveTypes.h:34
#define SC_TRY(expression)
Checks the value of the given expression and if failed, returns this value to caller.
Definition Result.h:48
A buffer of bytes with given alignment.
Definition AlignedStorage.h:29
[UniqueHandleDeclaration2Snippet]
Definition File.h:78
Read / Write pipe (Process stdin/stdout and IPC communication)
Definition File.h:215
Execute multiple child processes chaining input / output between them.
Definition Process.h:324
Result exec(const Process::StdOut &stdOut=Process::StdOut::Inherit{}, const Process::StdIn &stdIn=Process::StdIn::Inherit{}, const Process::StdErr &stdErr=Process::StdErr::Inherit{})
Launch the entire chain of processes and waits for the results (calling ProcessChain::waitForExitSync...
Definition Process.h:345
Result launch(const Process::StdOut &stdOut=Process::StdOut::Inherit{}, const Process::StdIn &stdIn=Process::StdIn::Inherit{}, const Process::StdErr &stdErr=Process::StdErr::Inherit{})
Launch the entire chain of processes.
Result pipe(Process &process, const Span< const StringSpan > cmd)
Add a process to the chain, with given arguments.
Result waitForExitSync()
Waits (blocking) for entire process chain to exit.
Reads current process environment variables.
Definition Process.h:373
bool contains(StringSpan variableName, size_t *index=nullptr)
Checks if an environment variable exists in current process.
bool get(size_t index, StringSpan &name, StringSpan &value) const
Get the environment variable at given index, returning its name and value.
size_t size() const
Returns the total number of environment variables for current process.
Definition Process.h:383
Wraps the code returned by a process that has exited.
Definition Process.h:18
Forks current process exiting child at end of process A fork duplicates a parent process execution st...
Definition Process.h:435
Result waitForChild()
Waits for child fork to finish execution.
State
Definition Process.h:451
@ Suspended
Start the forked process suspended (resume it with ProcessFork::resumeChildFork)
Definition Process.h:452
@ Immediate
Start the forked process immediately.
Definition Process.h:453
Side getSide() const
Obtain process parent / fork side.
Definition Process.h:448
FileDescriptor & getWritePipe()
Gets the descriptor to "write" something to the other side.
Side
Definition Process.h:442
@ ForkParent
Parent side of the fork.
Definition Process.h:443
@ ForkChild
Child side of the fork.
Definition Process.h:444
Result resumeChildFork()
Sends 1 byte on parentToFork to resume State::Paused child fork.
FileDescriptor & getReadPipe()
Gets the descriptor to "read" something from the other side.
Result fork(State state)
Forks current process (use ForkProcess::getType to know the side)
int32_t getExitStatus() const
Gets the return code from the exited child fork.
Definition Process.h:466
Native os handle to a process identifier.
Definition Process.h:30
bool windowsHide
[Windows] Hides child process window (default == Process::isWindowsConsoleSubsystem)
Definition Process.h:71
StdIn(const char(&item)[N])
Fills standard input with content of a C-String.
Definition Process.h:177
StdIn(StringSpan string)
Fills standard input with content of a StringSpan.
Definition Process.h:180
StdIn(Span< const char > span)
Fills standard input with content of a Span.
Definition Process.h:183
StdIn(Inherit)
Inherits child process Input from parent process.
Definition Process.h:174
StdOut(Span< char > span)
Read the process standard output/error into the given Span.
Definition Process.h:159
StdOut(Ignore)
Ignores child process standard output/error (child process output will be silenced)
Definition Process.h:153
StdOut(Inherit)
Inherits child process standard output/error (child process will print into parent process console)
Definition Process.h:156
StdStream(T &destination)
Read the process standard output/error into the given String / Buffer.
Definition Process.h:79
StdStream(FileDescriptor &&file)
Redirects child process standard output/error to a given file descriptor.
Definition Process.h:95
Execute a child process with standard file descriptors redirection.
Definition Process.h:68
int32_t getExitStatus() const
gets the return code from the exited child process (valid only after exec or waitForExitSync)
Definition Process.h:230
Result setEnvironment(StringSpan environmentVariable, StringSpan value)
Sets the environment variable for the newly spawned child process.
Result exec(Span< const StringSpan > cmd, const StdOut &stdOut=StdOut::Inherit{}, const StdIn &stdIn=StdIn::Inherit{}, const StdErr &stdErr=StdErr::Inherit{})
Executes a child process with the given arguments, waiting (blocking) until it's fully finished.
Definition Process.h:220
Result launch(Span< const StringSpan > cmd, const StdOut &stdOut=StdOut::Inherit{}, const StdIn &stdIn=StdIn::Inherit{}, const StdErr &stdErr=StdErr::Inherit{})
Launch child process with the given arguments.
Definition Process.h:204
Process(Span< native_char_t > commandMemory={}, Span< native_char_t > environmentMemory={})
Constructs a Process object passing (optional) memory storage for command and environment variables.
Definition Process.h:253
Options options
Options for the child process (hide console window etc.)
Definition Process.h:192
static bool isWindowsEmulatedProcess()
Returns true if we're emulating x64 on ARM64 or the inverse on Windows.
void inheritParentEnvironmentVariables(bool inherit)
Controls if the newly spawned child process will inherit parent process environment variables.
Definition Process.h:236
ProcessID processID
ID of the process (can be the same as handle on some OS)
Definition Process.h:191
static bool isWindowsConsoleSubsystem()
Returns true only under Windows if executable is compiled with /SUBSYSTEM:Console
static size_t getNumberOfProcessors()
Returns number of (virtual) processors available.
ProcessDescriptor handle
Handle to the OS process.
Definition Process.h:190
Result setWorkingDirectory(StringSpan processWorkingDirectory)
Sets the starting working directory of the process that will be launched / executed.
Result waitForExitSync()
Waits (blocking) for process to exit after launch. It can only be called if Process::launch succeeded...
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:12
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29
An read-only view over a string (to avoid including Strings library when parsing is not needed).
Definition StringSpan.h:37