5#include "../Common/CompilerMacrosExport.h"
6#ifndef SC_EXPORT_LIBRARY_PROCESS
7#define SC_EXPORT_LIBRARY_PROCESS 0
9#define SC_PROCESS_EXPORT SC_COMPILER_LIBRARY_EXPORT(SC_EXPORT_LIBRARY_PROCESS)
11#include "../Common/AlignedStorage.h"
12#include "../Common/Assert.h"
13#include "../Common/IGrowableBufferSpan.h"
14#include "../Common/IGrowableBufferStringPath.h"
15#include "../File/File.h"
16#include "ProcessError.h"
20SC_DECLARE_ASSERT_PROVIDER(ProcessAssert, SC_PROCESS_EXPORT);
22#define SC_PROCESS_ASSERT_RELEASE(e) SC_ASSERT_PROVIDER_RELEASE(SC::ProcessAssert, e)
23#define SC_PROCESS_ASSERT_DEBUG(e) SC_ASSERT_PROVIDER_DEBUG(SC::ProcessAssert, e)
24#define SC_PROCESS_TRUST_RESULT(expression) SC_PROCESS_ASSERT_RELEASE(expression)
26struct SC_PROCESS_EXPORT ProcessChain;
30 using Handle = detail::FileDescriptorDefinition::Handle;
31 static constexpr auto Invalid = detail::FileDescriptorDefinition::Invalid;
87 static constexpr size_t InlineCommandStorageCapacity = StringPath::MaxPath + 1024;
101 growableBuffer = &destination;
102 operation = Operation::GrowableBuffer;
108 operation = Operation::FileDescriptor;
109 (void)file.content.get(fileDescriptor,
110 Result::Error(ProcessResultCategory, ProcessError::InvalidOutputRedirection));
111 file.content.detach();
114 StdStream(GrowableBuffer<PipeDescriptor>& pipe)
116 operation = Operation::ExternalPipe;
117 pipeDescriptor = &pipe.content;
120 StdStream(
const StdStream&) =
delete;
121 StdStream(StdStream&&) =
delete;
122 StdStream& operator=(
const StdStream&) =
delete;
123 StdStream& operator=(StdStream&&) =
delete;
145 Operation operation = Operation::Inherit;
147 Span<const char> readableSpan;
148 Span<char>* writableSpan =
nullptr;
150 IGrowableBuffer* growableBuffer =
nullptr;
152 FileDescriptor::Handle fileDescriptor = ProcessDescriptor::Invalid;
165 StdOut(GrowableBuffer<StdOut::Ignore>) { operation = Operation::Ignore; }
168 StdOut(GrowableBuffer<StdOut::Inherit>) { operation = Operation::Inherit; }
169 StdOut(GrowableBuffer<StdOut>) { operation = Operation::Inherit; }
170 StdOut() { operation = Operation::Inherit; }
173 StdOut(GrowableBuffer<Span<char>>& span) { operation = Operation::WritableSpan; writableSpan = &span.content; span.setContentInDestructor =
false; }
175 using StdStream::StdStream;
180 using StdErr = StdOut;
188 StdIn(GrowableBuffer<Inherit>) { operation = Operation::Inherit; }
189 StdIn(GrowableBuffer<StdIn>) { operation = Operation::Inherit; }
190 StdIn() { operation = Operation::Inherit; }
193 template <
int N>
StdIn(GrowableBuffer<
const char [N]>& item) { operation = Operation::ReadableSpan; readableSpan = {item.content, N - 1}; }
196 StdIn(GrowableBuffer<StringSpan>
string) { operation = Operation::ReadableSpan; readableSpan =
string.content.toCharSpan();}
199 StdIn(GrowableBuffer<Span<const char>> span) { operation = Operation::ReadableSpan; readableSpan = span.content;}
201 using StdStream::StdStream;
209 ProcessDescriptor::Handle handle = ProcessDescriptor::Invalid;
221 template <
typename Out = StdOut,
typename In = StdIn,
typename Err = StdErr>
222 ResultProcess launch(Span<const StringSpan> cmd, Out&& stdOut = Out(), In&& stdIn = In(), Err&& stdErr = Err())
224 SC_TRY(formatArguments(cmd));
225 GrowableBuffer<typename TypeTraits::RemoveReference<Out>::type> gbOut = {stdOut};
226 GrowableBuffer<typename TypeTraits::RemoveReference<In>::type> gbIn = {stdIn};
227 GrowableBuffer<typename TypeTraits::RemoveReference<Err>::type> gbErr = {stdErr};
238 template <
typename Out = StdOut,
typename In = StdIn,
typename Err = StdErr>
239 ResultProcess exec(Span<const StringSpan> cmd, Out&& stdOut = Out(), In&& stdIn = In(), Err&& stdErr = Err())
241 SC_TRY(launch(cmd, stdOut, stdIn, stdErr));
242 return waitForExitSync();
269 Process(Span<native_char_t> commandMemory = {}, Span<native_char_t> environmentMemory = {})
270 : command({commandMemory}), environment({environmentMemory})
272 if (commandMemory.empty())
273 command = {commandStorage};
274 if (environmentMemory.empty())
275 environment = {environmentStorage};
279 ProcessExitStatus exitStatus;
281 FileDescriptor stdInFd;
282 FileDescriptor stdOutFd;
283 FileDescriptor stdErrFd;
285 ResultProcess launch(
const StdOut& stdOutput,
const StdIn& stdInput,
const StdErr& stdError);
287 ResultProcess formatArguments(Span<const StringSpan> cmd);
289 StringPath currentDirectory;
290#if SC_PLATFORM_WINDOWS
291 StringPath executablePathForLaunch;
292 bool executablePathLooksLikeFile =
false;
299 native_char_t commandStorage[InlineCommandStorageCapacity];
300 StringSpan::NativeWritable command;
301#if !SC_PLATFORM_WINDOWS
302 static constexpr size_t MAX_NUM_ARGUMENTS = 64;
303 size_t commandArgumentsByteOffset[MAX_NUM_ARGUMENTS];
304 size_t commandArgumentsNumber = 0;
307 native_char_t environmentStorage[4096 * 8];
308 StringSpan::NativeWritable environment;
310 static constexpr size_t MAX_NUM_ENVIRONMENT = 256;
312 size_t environmentByteOffset[MAX_NUM_ENVIRONMENT];
313 size_t environmentNumber = 0;
315 bool inheritEnv =
true;
317 friend struct ProcessChain;
318 ProcessChain* parent =
nullptr;
320 Process* next =
nullptr;
321 Process* prev =
nullptr;
324 friend struct ProcessFork;
325 ResultProcess launchImplementation();
326 ResultProcess launchForkChild(PipeDescriptor& pipe);
327 ResultProcess launchForkParent(PipeDescriptor& pipe,
const void* previousSignals);
358 template <
typename Out = Process::StdOut,
typename In = Process::StdIn,
typename Err = Process::StdErr>
361 GrowableBuffer<typename TypeTraits::RemoveReference<Out>::type> gbOut = {stdOut};
362 GrowableBuffer<typename TypeTraits::RemoveReference<In>::type> gbIn = {stdIn};
363 GrowableBuffer<typename TypeTraits::RemoveReference<Err>::type> gbErr = {stdErr};
364 return internalLaunch(gbOut, gbIn, gbErr);
373 template <
typename Out = Process::StdOut,
typename In = Process::StdIn,
typename Err = Process::StdErr>
376 SC_TRY(launch(stdOut, stdIn, stdErr));
377 return waitForExitSync();
384 struct ProcessLinkedList
389 [[nodiscard]]
bool isEmpty()
const {
return front ==
nullptr; }
392 void queueBack(Process& process);
394 ProcessLinkedList processes;
412 [[nodiscard]]
size_t size()
const {
return numberOfEnvironment; }
418 [[nodiscard]]
bool get(
size_t index, StringSpan& name, StringSpan& value)
const;
424 [[nodiscard]]
bool contains(StringSpan variableName,
size_t* index =
nullptr)
const;
430 [[nodiscard]]
bool get(StringSpan variableName, StringSpan& value)
const;
433 size_t numberOfEnvironment = 0;
434#if SC_PLATFORM_WINDOWS
435 static constexpr size_t MAX_ENVIRONMENTS = 256;
437 StringSpan envStrings[MAX_ENVIRONMENTS];
438 wchar_t* environment =
nullptr;
440 char** environment =
nullptr;
510 Side side = ForkParent;
511#if SC_PLATFORM_WINDOWS
512 ProcessDescriptor::Handle processHandle = ProcessDescriptor::Invalid;
513 ProcessDescriptor::Handle threadHandle = ProcessDescriptor::Invalid;
[UniqueHandleDeclaration2Snippet]
Definition File.h:130
Read / Write pipe (Process stdin/stdout and IPC communication)
Definition File.h:302
Execute multiple child processes chaining input / output between them.
Definition Process.h:347
ResultProcess launch(Out &&stdOut=Out(), In &&stdIn=In(), Err &&stdErr=Err())
Launch the entire chain of processes.
Definition Process.h:359
ResultProcess waitForExitSync()
Waits (blocking) for entire process chain to exit.
ResultProcess pipe(Process &process, const Span< const StringSpan > cmd)
Add a process to the chain, with given arguments.
ResultProcess exec(Out &&stdOut=Out(), In &&stdIn=In(), Err &&stdErr=Err())
Launch the entire chain of processes and waits for the results (calling ProcessChain::waitForExitSync...
Definition Process.h:374
Reads current process environment variables.
Definition Process.h:402
bool get(size_t index, StringSpan &name, StringSpan &value) const
Get the environment variable at given index, returning its name and value.
bool get(StringSpan variableName, StringSpan &value) const
Gets the value of an environment variable from current process.
size_t size() const
Returns the total number of environment variables for current process.
Definition Process.h:412
bool contains(StringSpan variableName, size_t *index=nullptr) const
Checks if an environment variable exists in current process.
Wraps the code returned by a process that has exited.
Definition Process.h:36
Forks current process exiting child at end of process A fork duplicates a parent process execution st...
Definition Process.h:470
ResultProcess waitForChild()
Waits for child fork to finish execution.
State
Definition Process.h:486
@ Suspended
Start the forked process suspended (resume it with ProcessFork::resumeChildFork)
Definition Process.h:487
@ Immediate
Start the forked process immediately.
Definition Process.h:488
ResultProcess fork(State state)
Forks current process (use ForkProcess::getType to know the side)
Side getSide() const
Obtain process parent / fork side.
Definition Process.h:483
FileDescriptor & getWritePipe()
Gets the descriptor to "write" something to the other side.
Side
Definition Process.h:477
@ ForkParent
Parent side of the fork.
Definition Process.h:478
@ ForkChild
Child side of the fork.
Definition Process.h:479
FileDescriptor & getReadPipe()
Gets the descriptor to "read" something from the other side.
ResultProcess resumeChildFork()
Sends 1 byte on parentToFork to resume State::Paused child fork.
int32_t getExitStatus() const
Gets the return code from the exited child fork.
Definition Process.h:501
Native os handle to a process identifier.
Definition Process.h:48
bool windowsHide
[Windows] Hides child process window
Definition Process.h:91
bool windowsCreateNewProcessGroup
[Windows] Creates a console process group rooted at the child
Definition Process.h:92
StdIn(GrowableBuffer< Span< const char > > span)
Fills standard input with content of a Span.
Definition Process.h:199
StdIn(GrowableBuffer< Inherit >)
Inherits child process Input from parent process.
Definition Process.h:188
StdIn(GrowableBuffer< const char[N]> &item)
Fills standard input with content of a C-String.
Definition Process.h:193
StdIn(GrowableBuffer< StringSpan > string)
Fills standard input with content of a StringSpan.
Definition Process.h:196
StdOut(GrowableBuffer< Span< char > > &span)
Read the process standard output/error into the given Span.
Definition Process.h:173
StdOut(GrowableBuffer< StdOut::Inherit >)
Inherits child process standard output/error (child process will print into parent process console)
Definition Process.h:168
StdOut(GrowableBuffer< StdOut::Ignore >)
Ignores child process standard output/error (child process output will be silenced)
Definition Process.h:165
StdStream(GrowableBuffer< FileDescriptor > &file)
Redirects child process standard output/error to a given file descriptor.
Definition Process.h:106
StdStream(IGrowableBuffer &destination)
Read the process standard output/error into the given String / Buffer.
Definition Process.h:99
Execute a child process with standard file descriptors redirection.
Definition Process.h:86
int32_t getExitStatus() const
gets the return code from the exited child process (valid only after exec or waitForExitSync)
Definition Process.h:246
ResultProcess 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.
Definition Process.h:239
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:269
Options options
Options for the child process (hide console window etc.)
Definition Process.h:207
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:252
ResultProcess launch(Span< const StringSpan > cmd, Out &&stdOut=Out(), In &&stdIn=In(), Err &&stdErr=Err())
Launch child process with the given arguments.
Definition Process.h:222
ResultProcess setWorkingDirectory(StringSpan processWorkingDirectory)
Sets the starting working directory of the process that will be launched / executed.
ProcessID processID
ID of the process (can be the same as handle on Posix)
Definition Process.h:206
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.
ResultProcess waitForExitSync()
Waits (blocking) for process to exit after launch. It can only be called if Process::launch succeeded...
ResultProcess setEnvironment(StringSpan environmentVariable, StringSpan value)
Sets the environment variable for the newly spawned child process.
Process result retaining optional backend and native platform details.
Definition ProcessError.h:62