4#include "Stroika/Foundation/StroikaPreComp.h"
8#if qStroika_Foundation_Common_Platform_POSIX
11#include <sys/resource.h>
23#include "Stroika/Foundation/Containers/Sequence.h"
25#if qStroika_Foundation_Common_Platform_Windows
26#include "Platform/Windows/Exception.h"
28#include "Stroika/Foundation/Execution/Activity.h"
29#include "Stroika/Foundation/Execution/CommandLine.h"
30#include "Stroika/Foundation/Execution/Exceptions.h"
32#include "Stroika/Foundation/Execution/Module.h"
35#include "Stroika/Foundation/IO/FileSystem/FileUtils.h"
37#include "Stroika/Foundation/Memory/Common.h"
40#include "Stroika/Foundation/Streams/MemoryStream.h"
41#include "Stroika/Foundation/Streams/TextToBinary.h"
46#include "ProcessRunner.h"
53using namespace Stroika::Foundation::Debug;
55using namespace Stroika::Foundation::Streams;
56using namespace Stroika::Foundation::Traversal;
64#if USE_NOISY_TRACE_IN_THIS_MODULE_
68#if qStroika_Foundation_Common_Platform_POSIX
72 inline void CLOSE_ (
int& fd)
noexcept
74 if (fd >= 0) [[likely]] {
82#if qStroika_Foundation_Common_Platform_POSIX
84 static const int kMaxFD_ = [] () ->
int {
86 constexpr bool kUseSysConf_ =
true;
87#if _BSD_SOURCE || _XOPEN_SOURCE >= 500
88 [[maybe_unused]]
constexpr bool kUseGetDTableSize_ =
true;
90 [[maybe_unused]]
constexpr bool kUseGetDTableSize_ =
false;
92 constexpr bool kUseGetRLimit_ =
true;
93 if constexpr (kUseSysConf_) {
94 result = ::sysconf (_SC_OPEN_MAX);
97 else if constexpr (kUseSysConf_) {
98 result = getdtablesize ();
100 else if constexpr (kUseGetRLimit_) {
102 if (::getrlimit (RLIMIT_NOFILE, &fds) == 0) {
117 Assert (result < 4 * 1024 * 1024);
118 DbgTrace (
"::sysconf (_SC_OPEN_MAX) = {}"_f, result);
124#if qStroika_Foundation_Common_Platform_POSIX
136#if qStroika_Foundation_Common_Platform_POSIX
142 constexpr bool kUseSpawn_ =
false;
144extern char** environ;
147#if qStroika_Foundation_Common_Platform_Windows
151 AutoHANDLE_ (HANDLE h = INVALID_HANDLE_VALUE)
155 AutoHANDLE_ (
const AutoHANDLE_&) =
delete;
160 AutoHANDLE_& operator= (
const AutoHANDLE_& rhs)
164 fHandle = rhs.fHandle;
168 operator HANDLE ()
const
178 if (fHandle != INVALID_HANDLE_VALUE) {
179 Verify (::CloseHandle (fHandle));
180 fHandle = INVALID_HANDLE_VALUE;
183 void ReplaceHandleAsNonInheritable ()
185 HANDLE result = INVALID_HANDLE_VALUE;
186 Verify (::DuplicateHandle (::GetCurrentProcess (), fHandle, ::GetCurrentProcess (), &result, 0, FALSE, DUPLICATE_SAME_ACCESS));
187 Verify (::CloseHandle (fHandle));
194 inline void SAFE_HANDLE_CLOSER_ (HANDLE* h)
197 if (*h != INVALID_HANDLE_VALUE) {
198 Verify (::CloseHandle (*h));
199 *h = INVALID_HANDLE_VALUE;
206 template <Common::IAnyOf<
char,
wchar_t> CHAR_T>
207 struct String2ContigArrayCStrs_ {
208 StackBuffer<CHAR_T> fBytesBuffer;
209 StackBuffer<CHAR_T*, 10 *
sizeof (
void*)> fPtrsBuffer;
210 String2ContigArrayCStrs_ (
const Mapping<basic_string<CHAR_T>, basic_string<CHAR_T>>& data)
211 : String2ContigArrayCStrs_{data.template Map<
Iterable<basic_string<CHAR_T>>> (
212 [] (auto kvp) -> basic_string<CHAR_T> {
return kvp.fKey + SDKSTR (
"=") + kvp.fValue; })}
215 String2ContigArrayCStrs_ (
const Iterable<basic_string<CHAR_T>>& data)
217 StackBuffer<size_t> argsIdx;
218 size_t bufferIndex = 0;
219 for (
const basic_string<CHAR_T>& i : data) {
220 fBytesBuffer.push_back (span{i});
221 fBytesBuffer.push_back (
'\0');
222 argsIdx.push_back (bufferIndex);
223 bufferIndex = fBytesBuffer.GetSize ();
225 fBytesBuffer.push_back (
'\0');
226 auto freeze = fBytesBuffer.
begin ();
227 for (
size_t i : argsIdx) {
228 fPtrsBuffer.push_back (freeze + i);
230 fPtrsBuffer.push_back (
nullptr);
232 String2ContigArrayCStrs_ () =
delete;
233 String2ContigArrayCStrs_ (
const String2ContigArrayCStrs_&) =
delete;
234 String2ContigArrayCStrs_ (String2ContigArrayCStrs_&&) =
delete;
238#if qStroika_Foundation_Common_Platform_Windows
243#ifndef qUsePeekNamedPipe_
244#define qUsePeekNamedPipe_ 0
263 constexpr size_t kPipeBufSize_ = 256 * 1024;
264 constexpr size_t kReadBufSize_ = 32 * 1024;
273String ProcessRunner::Exception::mkMsg_ (
const String& errorMessage,
const optional<String>& stderrSubset,
274 const optional<ExitStatusType>& wExitStatus,
const optional<SignalID>& wTermSig)
281 extraMsg <<
"exit status {}"_f(
int (*wExitStatus));
284 if (not extraMsg.
empty ()) {
287 extraMsg <<
"terminated by signal {}"_f(
int (*wTermSig));
289 if (not extraMsg.
empty ()) {
290 sb <<
": "sv << extraMsg;
294 sb <<
" (captured stderr: "sv
295 << stderrSubset->ReplaceAll (
"\\s+"_RegEx,
" "sv).LimitLength (100, StringShorteningPreference::ePreferKeepRight) <<
")"sv;
305void ProcessRunner::ProcessResultType::ThrowIfFailed ()
307 if (fExitStatus and *fExitStatus != 0) {
310 if (fTerminatedByUncaughtSignalNumber and *fTerminatedByUncaughtSignalNumber != 0) {
311 Throw (
Exception{
"Child process failed", nullopt, nullopt, *fTerminatedByUncaughtSignalNumber});
320ProcessRunner::BackgroundProcess::BackgroundProcess ()
321 : fRep_{make_shared<Rep_> ()}
329 t.ThrowIfDoneWithException ();
331 if (o->fExitStatus and o->fExitStatus != ExitStatusType{}) {
334 if (o->fTerminatedByUncaughtSignalNumber) {
344 DurationSeconds remaining = timeout;
345 while (remaining > DurationSeconds{0}) {
346 if (
auto pr = GetChildProcessID ()) {
350 remaining -= DurationSeconds{1};
384 if (optional<pid_t> o = fRep_->fPID) {
385#if qStroika_Foundation_Common_Platform_POSIX
386 ::kill (SIGTERM, *o);
387#elif qStroika_Foundation_Common_Platform_Windows
389 HANDLE processHandle = ::OpenProcess (PROCESS_TERMINATE,
false, *o);
390 if (processHandle !=
nullptr) {
391 ::TerminateProcess (processHandle, 1);
392 ::CloseHandle (processHandle);
395 DbgTrace (
"::OpenProcess returned null: GetLastError () = {}"_f, GetLastError ());
422 r.
Add (i.fKey.AsSDKString (), i.fValue.AsSDKString ());
429#if qStroika_Foundation_Common_Platform_POSIX
431#elif qStroika_Foundation_Common_Platform_Windows
434 r.
Add (SDKSTR (
"PATH"), path);
448 auto activity =
LazyEvalActivity ([
this] () ->
String {
return "running '{}'"_f(this->GetCommandLine ()); });
450 if (timeout == Time::kInfinity) {
455 CreateRunnable_ (&pr,
nullptr, progress) ();
456 pr->value_or (ProcessResultType{}).ThrowIfFailed ();
461 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { bp.Terminate (); });
463 bp.PropagateIfException ();
465 bp.GetProcessResult ().value_or (ProcessResultType{}).ThrowIfFailed ();
471 if (timeout == Time::kInfinity) {
472 if (processResult ==
nullptr) {
473 CreateRunnable_ (
nullptr,
nullptr, progress) ();
477 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { *processResult = pr.
load (); });
478 CreateRunnable_ (&pr,
nullptr, progress) ();
482 if (processResult ==
nullptr) {
483 Thread::Ptr t =
Thread::New (CreateRunnable_ (
nullptr,
nullptr, progress), Thread::eAutoStart,
"ProcessRunner thread"_k);
488 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { *processResult = pr.
load (); });
489 Thread::Ptr t =
Thread::New (CreateRunnable_ (&pr,
nullptr, progress), Thread::eAutoStart,
"ProcessRunner thread"_k);
505 : BinaryToText::Reader::New (readFromBinStrm);
509 if (not cmdStdInValue.empty ()) {
510 auto outStream = stringOpts.fOutputCodeCvt ? TextToBinary::Writer::New (useStdIn, *stringOpts.fOutputCodeCvt)
511 : TextToBinary::Writer::New (useStdIn);
512 outStream.Write (cmdStdInValue);
514 Assert (useStdIn.GetReadOffset () == 0);
516 Run (useStdIn, useStdOut, useStdErr, progress, timeout);
519 Assert (useStdOut.GetReadOffset () == 0);
520 Assert (useStdErr.GetReadOffset () == 0);
521 return make_tuple (mkReadStream (useStdOut).ReadAll (), mkReadStream (useStdErr).ReadAll ());
524 String out = mkReadStream (useStdOut).ReadAll ();
525 String err = mkReadStream (useStdErr).ReadAll ();
526#if qStroika_Foundation_Debug_DefaultTracingOn
527 DbgTrace (
"Captured stdout: {}"_f, out);
528 DbgTrace (
"Captured stderr: {}"_f, err);
530 Throw (
Exception{e.fFailureMessage, err, e.fExitStatus, e.fTermSignal});
534 String out = mkReadStream (useStdOut).ReadAll ();
535 String err = mkReadStream (useStdErr).ReadAll ();
536#if qStroika_Foundation_Debug_DefaultTracingOn
537 DbgTrace (
"Captured stdout: {}"_f, out);
538 DbgTrace (
"Captured stderr: {}"_f, err);
540 exception_ptr e = current_exception ();
550 this->fStdOut_ = out;
551 this->fStdErr_ = error;
552 BackgroundProcess result;
553 result.fRep_->fProcessRunner =
554 Thread::New (CreateRunnable_ (&result.fRep_->fResult,
nullptr, progress), Thread::eAutoStart,
"ProcessRunner background thread"sv);
561 BackgroundProcess result;
562 result.fRep_->fProcessRunner =
563 Thread::New (CreateRunnable_ (&result.fRep_->fResult,
nullptr, progress), Thread::eAutoStart,
"ProcessRunner background thread"sv);
567#if qStroika_Foundation_Common_Platform_POSIX
570 void Process_Runner_POSIX_ (
Synchronized<optional<ProcessRunner::ProcessResultType>>* processResult,
Synchronized<optional<pid_t>>* runningPID,
575 optional<mode_t> umask = options.fChildUMask;
578 "...,cmdLine='{}',currentDir='{}',..."_f, cmdLine,
582 char trailingStderrBuf[256];
583 char* trailingStderrBufNextByte2WriteAt = begin (trailingStderrBuf);
584 size_t trailingStderrBufNWritten{};
593 int jStdin[2]{-1, -1};
594 int jStdout[2]{-1, -1};
595 int jStderr[2]{-1, -1};
596 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept {
597 ::CLOSE_ (jStdin[0]);
598 ::CLOSE_ (jStdin[1]);
599 ::CLOSE_ (jStdout[0]);
600 ::CLOSE_ (jStdout[1]);
601 ::CLOSE_ (jStderr[0]);
602 ::CLOSE_ (jStderr[1]);
608 jStdin[0] = ::open (
"/dev/null", O_RDONLY);
614 jStdout[1] = ::open (
"/dev/null", O_WRONLY);
620 jStderr[1] = ::open (
"/dev/null", O_WRONLY);
623 Assert (in ==
nullptr or (jStdin[0] >= 3 and jStdin[1] >= 3));
624 Assert (out ==
nullptr or (jStdout[0] >= 3 and jStdout[1] >= 3));
625 Assert (err ==
nullptr or (jStderr[0] >= 3 and jStderr[1] >= 3));
626 DbgTrace (
"jStdout[0-CHILD] = {} and jStdout[1-PARENT] = {}"_f, jStdout[0], jStdout[1]);
633 const char* thisEXEPath_cstr =
nullptr;
634 char** thisEXECArgv =
nullptr;
636 String2ContigArrayCStrs_<char> execDataArgs{
638 thisEXEPath_cstr = execDataArgs.fBytesBuffer.data ();
639 thisEXECArgv = execDataArgs.fPtrsBuffer.data ();
648 if (not kUseSpawn_ and thisEXEPath_cstr[0] ==
'/' and ::access (thisEXEPath_cstr, R_OK | X_OK) < 0) {
650#if USE_NOISY_TRACE_IN_THIS_MODULE_
658 posix_spawn_file_actions_t file_actions{};
665 posix_spawn_file_actions_init (&file_actions);
666 posix_spawn_file_actions_addclose (&file_actions, jStdin[0]);
667 posix_spawn_file_actions_addclose (&file_actions, jStdin[0]);
668 posix_spawn_file_actions_adddup2 (&file_actions, jStdout[1], 1);
669 posix_spawn_file_actions_addclose (&file_actions, jStdout[0]);
670 posix_spawn_file_actions_adddup2 (&file_actions, jStderr[1], 2);
671 posix_spawn_file_actions_addclose (&file_actions, jStderr[1]);
673 posix_spawnattr_t* attr =
nullptr;
674 int status = ::posix_spawnp (&childPID, thisEXEPath_cstr, &file_actions, attr, thisEXECArgv, environ);
680 childPID = DoFork_ ();
684 (void)::umask (*umask);
691 DISABLE_COMPILER_GCC_WARNING_START (
"GCC diagnostic ignored \"-Wunused-result\"")
692 (void)::chdir (useCWD.c_str ());
693 DISABLE_COMPILER_GCC_WARNING_END (
"GCC diagnostic ignored \"-Wunused-result\"")
694 if (options.fDetached.value_or (false)) {
716 int useSTDIN = jStdin[0];
717 int useSTDOUT = jStdout[1];
718 int useSTDERR = jStderr[1];
719 Assert (useSTDIN >= 0 and useSTDOUT >= 0 and useSTDERR >= 0);
723 ::dup2 (useSTDIN, 0);
724 ::dup2 (useSTDOUT, 1);
725 ::dup2 (useSTDERR, 2);
728 ::close (jStdout[0]);
729 ::close (jStdout[1]);
730 ::close (jStderr[0]);
731 ::close (jStderr[1]);
733 constexpr bool kCloseAllExtraneousFDsInChild_ =
true;
734 if (kCloseAllExtraneousFDsInChild_) {
736 for (
int i = 3; i < kMaxFD_; ++i) {
740 [[maybe_unused]]
int r = ::execvp (thisEXEPath_cstr, thisEXECArgv);
741#if USE_NOISY_TRACE_IN_THIS_MODULE_
744 myfile.open (
"/tmp/Stroika-ProcessRunner-Exec-Failed-Debug-File.txt");
745 myfile <<
"thisEXEPath_cstr = " << thisEXEPath_cstr << endl;
746 myfile <<
"r = " << r <<
" and errno = " << errno << endl;
749 ::_exit (EXIT_FAILURE);
752 ::_exit (EXIT_FAILURE);
757 Assert (childPID > 0);
759 constexpr size_t kStackBufReadAtATimeSize_ = 10 * 1024;
761#if USE_NOISY_TRACE_IN_THIS_MODULE_
762 DbgTrace (
"In Parent Fork: child process PID={}"_f, childPID);
764 if (runningPID !=
nullptr) {
765 runningPID->store (childPID);
770 int& useSTDIN = jStdin[1];
771 int& useSTDOUT = jStdout[0];
772 int& useSTDERR = jStderr[0];
781 if (useSTDIN != -1) {
784 if (useSTDOUT != -1) {
787 if (useSTDERR != -1) {
792 auto readALittleFromProcess = [&] (
int fd,
const OutputStream::Ptr<byte>& stream,
bool write2StdErrCache,
bool* eof =
nullptr,
793 bool* maybeMoreData =
nullptr) ->
void {
795 if (maybeMoreData !=
nullptr) {
796 *maybeMoreData =
false;
798 if (eof !=
nullptr) {
803 uint8_t buf[kStackBufReadAtATimeSize_];
805#if USE_NOISY_TRACE_IN_THIS_MODULE_
806 int skipedThisMany{};
808 while ((nBytesRead = ::read (fd, buf,
sizeof (buf))) > 0) {
809 Assert (nBytesRead <=
sizeof (buf));
810 if (stream !=
nullptr) {
811 stream.Write (span{buf,
static_cast<size_t> (nBytesRead)});
813 if (write2StdErrCache) {
814 for (
size_t i = 0; i < nBytesRead; ++i) {
815 Assert (&trailingStderrBuf[0] <= trailingStderrBufNextByte2WriteAt and
816 trailingStderrBufNextByte2WriteAt < end (trailingStderrBuf));
817 *trailingStderrBufNextByte2WriteAt = buf[i];
818 ++trailingStderrBufNWritten;
819 ++trailingStderrBufNextByte2WriteAt;
820 if (trailingStderrBufNextByte2WriteAt == end (trailingStderrBuf)) {
821 trailingStderrBufNextByte2WriteAt = begin (trailingStderrBuf);
823 Assert (&trailingStderrBuf[0] <= trailingStderrBufNextByte2WriteAt and
824 trailingStderrBufNextByte2WriteAt < end (trailingStderrBuf));
827#if USE_NOISY_TRACE_IN_THIS_MODULE_
828 if (errno == EAGAIN) {
830 if (skipedThisMany++ < 100) {
834 DbgTrace (
"skipped {} spamming EAGAINs"_f, skipedThisMany);
838 buf[(nBytesRead == Memory::NEltsOf (buf)) ? (Memory::NEltsOf (buf) - 1) : nBytesRead] =
'\0';
839 DbgTrace (
"read from process (fd={}) nBytesRead = {}: {}"_f, fd, nBytesRead,
843#if USE_NOISY_TRACE_IN_THIS_MODULE_
844 DbgTrace (
"from (fd={}) nBytesRead = {}, errno={}"_f, fd, nBytesRead, errno);
846 if (nBytesRead < 0) {
847 if (errno != EINTR and errno != EAGAIN) {
851 if (eof !=
nullptr) {
852 *eof = (nBytesRead == 0);
854 if (maybeMoreData !=
nullptr) {
855 *maybeMoreData = (nBytesRead > 0) or (nBytesRead < 0 and errno == EINTR);
859 bool maybeMoreData =
true;
860 while (maybeMoreData) {
861 readALittleFromProcess (fd, stream, write2StdErrCache,
nullptr, &maybeMoreData);
871 (void)waiter.WaitQuietly (1s);
872 readALittleFromProcess (fd, stream, write2StdErrCache, &eof);
877 byte stdinBuf[kStackBufReadAtATimeSize_];
881 if (optional<span<byte>> bytesReadFromStdIn = in.
ReadNonBlocking (span{stdinBuf})) {
882 Assert (bytesReadFromStdIn->size () <= Memory::NEltsOf (stdinBuf));
883 if (bytesReadFromStdIn->empty ()) {
887 const byte* e = bytesReadFromStdIn->data () + bytesReadFromStdIn->size ();
888 for (
const byte* i = bytesReadFromStdIn->data (); i != e;) {
890 readSoNotBlocking (useSTDOUT, out,
false);
891 readSoNotBlocking (useSTDERR, err,
true);
893 int tmp = ::write (useSTDIN, i, e - i);
895 if (tmp < 0 and (errno == EAGAIN or errno == EWOULDBLOCK)) {
900 Assert (bytesWritten >= 0);
901 Assert (bytesWritten <= (e - i));
903 if (bytesWritten == 0) {
915 readSoNotBlocking (useSTDOUT, out,
false);
916 readSoNotBlocking (useSTDERR, err,
true);
924 readTilEOF (useSTDOUT, out,
false);
925 readTilEOF (useSTDERR, err,
true);
934 if (processResult !=
nullptr) {
937 WIFSIGNALED (status) ? WTERMSIG (status) : optional<int> ()});
939 else if (result != childPID or not WIFEXITED (status) or WEXITSTATUS (status) != 0) {
941 DbgTrace (
"childPID={}, result={}, status={}, WIFEXITED={}, WEXITSTATUS={}, WIFSIGNALED={}"_f,
static_cast<int> (childPID),
942 result, status, WIFEXITED (status), WEXITSTATUS (status), WIFSIGNALED (status));
943 if (processResult ==
nullptr) {
945 if (trailingStderrBufNWritten > Memory::NEltsOf (trailingStderrBuf)) {
946 stderrMsg <<
"..."sv;
947 stderrMsg <<
String::FromLatin1 (Memory::ConstSpan (span{trailingStderrBufNextByte2WriteAt, end (trailingStderrBuf)}));
949 stderrMsg <<
String::FromLatin1 (Memory::ConstSpan (span{begin (trailingStderrBuf), trailingStderrBufNextByte2WriteAt}));
951 WIFEXITED (status) ? WEXITSTATUS (status) : optional<uint8_t>{},
952 WIFSIGNALED (status) ? WTERMSIG (status) : optional<uint8_t>{}});
960#if qStroika_Foundation_Common_Platform_Windows
962 void Process_Runner_Windows_ (
Synchronized<optional<ProcessRunner::ProcessResultType>>* processResult,
964 const optional<filesystem::path>& executable,
const CommandLine& cmdLine,
const ProcessRunner::Options& options,
969 "...,cmdLine='{}',currentDir={},..."_f, cmdLine,
982 AutoHANDLE_ jStdin[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
983 AutoHANDLE_ jStdout[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
984 AutoHANDLE_ jStderr[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
986 PROCESS_INFORMATION processInfo{};
987 processInfo.hProcess = INVALID_HANDLE_VALUE;
988 processInfo.hThread = INVALID_HANDLE_VALUE;
992 SECURITY_DESCRIPTOR sd{};
993 Verify (::InitializeSecurityDescriptor (&sd, SECURITY_DESCRIPTOR_REVISION));
994 Verify (::SetSecurityDescriptorDacl (&sd,
true, 0,
false));
995 SECURITY_ATTRIBUTES sa = {
sizeof (SECURITY_ATTRIBUTES), &sd,
true};
997 Verify (::CreatePipe (&jStdin[1], &jStdin[0], &sa, kPipeBufSize_));
1000 Verify (::CreatePipe (&jStdout[1], &jStdout[0], &sa, kPipeBufSize_));
1003 Verify (::CreatePipe (&jStderr[1], &jStderr[0], &sa, kPipeBufSize_));
1010 jStdin[0].ReplaceHandleAsNonInheritable ();
1013 jStdout[1].ReplaceHandleAsNonInheritable ();
1016 jStderr[1].ReplaceHandleAsNonInheritable ();
1020 STARTUPINFO startInfo{};
1021 startInfo.cb =
sizeof (startInfo);
1022 startInfo.hStdInput = jStdin[1];
1023 startInfo.hStdOutput = jStdout[0];
1024 startInfo.hStdError = jStderr[0];
1025 startInfo.dwFlags |= STARTF_USESTDHANDLES;
1027 DWORD createProcFlags{NORMAL_PRIORITY_CLASS};
1028 if (options.fCreateNoWindow) {
1029 createProcFlags |= CREATE_NO_WINDOW;
1031 else if (options.fDetached.value_or (
false)) {
1033 createProcFlags |= DETACHED_PROCESS;
1039 bool bInheritHandles =
true;
1041 TCHAR cmdLineBuf[32768];
1042 Characters::CString::Copy (cmdLineBuf, Memory::NEltsOf (cmdLineBuf), cmdLine.
As<
String> ().
AsSDKString ().c_str ());
1044 optional<filesystem::path> useEXEPath = executable;
1047#if qStroika_Foundation_Debug_AssertionsChecked
1050 DbgTrace (
"Warning: Cannot find exe '{}' in PATH ({})"_f, useEXEPath,
kPath ());
1056 if (cmdArgs.size () >= 1) {
1057 filesystem::path exe2Find = cmdArgs[0].As<filesystem::path> ();
1059 DbgTrace (
"Warning: Cannot find exe '{}' in PATH ({})"_f, exe2Find,
kPath ());
1065 unique_ptr<String2ContigArrayCStrs_<SDKChar>> envBuffer;
1066 LPVOID lpEnvironment =
nullptr;
1067 if (options.fEnvironment) {
1069 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*oep));
1072 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*om));
1075 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*oms));
1078 lpEnvironment = envBuffer->fBytesBuffer.data ();
1079 if constexpr (same_as<SDKChar, wchar_t>) {
1080 createProcFlags |= CREATE_UNICODE_ENVIRONMENT;
1088 ::CreateProcess (useEXEPath == nullopt ?
nullptr : useEXEPath->c_str (), cmdLineBuf, nullptr, nullptr, bInheritHandles,
1089 createProcFlags, lpEnvironment, useCWD.c_str (), &startInfo, &processInfo));
1092 if (runningPID !=
nullptr) {
1093 runningPID->store (processInfo.dwProcessId);
1101 jStdout[0].Close ();
1102 jStderr[0].Close ();
1105 AutoHANDLE_& useSTDIN = jStdin[0];
1106 Assert (jStdin[1] == INVALID_HANDLE_VALUE);
1107 AutoHANDLE_& useSTDOUT = jStdout[1];
1108 Assert (jStdout[0] == INVALID_HANDLE_VALUE);
1109 AutoHANDLE_& useSTDERR = jStderr[1];
1110 Assert (jStderr[0] == INVALID_HANDLE_VALUE);
1112 constexpr size_t kStackBufReadAtATimeSize_ = 10 * 1024;
1115 if (p == INVALID_HANDLE_VALUE) {
1118 byte buf[kReadBufSize_];
1119#if qUsePeekNamedPipe_
1120 DWORD nBytesAvail{};
1126#
if qUsePeekNamedPipe_
1127 ::PeekNamedPipe (p,
nullptr,
nullptr,
nullptr, &nBytesAvail,
nullptr) and nBytesAvail != 0 and
1129 ::ReadFile (p, buf,
sizeof (buf), &nBytesRead,
nullptr) and nBytesRead > 0) {
1131 o.Write (span{buf, nBytesRead});
1133#if USE_NOISY_TRACE_IN_THIS_MODULE_
1134 buf[(nBytesRead == Memory::NEltsOf (buf)) ? (Memory::NEltsOf (buf) - 1) : nBytesRead] = byte{
'\0'};
1135 DbgTrace (
"read from process (fd={}) nBytesRead = {}: {}"_f, p, nBytesRead, buf);
1140 if (processInfo.hProcess != INVALID_HANDLE_VALUE) {
1146 auto mkPipeNoWait_ = [] (HANDLE ioHandle) ->
void {
1147 if (ioHandle != INVALID_HANDLE_VALUE) {
1148 DWORD stdinMode = 0;
1149 Verify (::GetNamedPipeHandleState (ioHandle, &stdinMode,
nullptr,
nullptr,
nullptr,
nullptr, 0));
1150 stdinMode |= PIPE_NOWAIT;
1151 Verify (::SetNamedPipeHandleState (ioHandle, &stdinMode,
nullptr,
nullptr));
1154 mkPipeNoWait_ (useSTDIN);
1155 mkPipeNoWait_ (useSTDOUT);
1156 mkPipeNoWait_ (useSTDERR);
1162 if (in !=
nullptr) {
1163 byte stdinBuf[kStackBufReadAtATimeSize_];
1165 while (
size_t nbytes = in.
ReadBlocking (span{stdinBuf}).size ()) {
1166 Assert (nbytes <= Memory::NEltsOf (stdinBuf));
1167 const byte* p = begin (stdinBuf);
1168 const byte* e = p + nbytes;
1171 if (::WriteFile (useSTDIN, p, Math::PinToMaxForType<DWORD> (e - p), &written,
nullptr) == 0) {
1172 DWORD lastErr = ::GetLastError ();
1178 if (lastErr != ERROR_SUCCESS and lastErr != ERROR_NO_MORE_FILES and lastErr != ERROR_PIPE_BUSY and
1179 lastErr != ERROR_NO_DATA) {
1180 DbgTrace (
"in RunExternalProcess_ - throwing {} while fill in stdin"_f, lastErr);
1181 ThrowSystemErrNo (lastErr);
1184 Assert (written <=
static_cast<size_t> (e - p));
1188 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1189 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1191 if (p < e and written == 0) {
1198 if (Time::GetTickCount () > timeoutAt) {
1199 DbgTrace (_T (
"process timed out (writing initial data) - so throwing up!"));
1201 (void)::TerminateProcess (processInfo.hProcess, -1);
1202 Throw (Execution::Platform::Windows::Exception (ERROR_TIMEOUT));
1217 int timesWaited = 0;
1226 HANDLE events[1] = {processInfo.hProcess};
1233 double remainingTimeout = (timesWaited <= 5) ? 0.1 : 0.5;
1234 DWORD waitResult = ::WaitForMultipleObjects (
static_cast<DWORD
> (Memory::NEltsOf (events)), events,
false,
1235 static_cast<int> (remainingTimeout * 1000));
1238 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1239 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1240 switch (waitResult) {
1241 case WAIT_OBJECT_0: {
1242 DbgTrace (
"external process finished (DONE)"_f);
1244 goto DoneWithProcess;
1246 case WAIT_TIMEOUT: {
1247 DbgTrace (
"still waiting for external process output (WAIT_TIMEOUT)"_f);
1253 DWORD processExitCode{};
1254 Verify (::GetExitCodeProcess (processInfo.hProcess, &processExitCode));
1256 SAFE_HANDLE_CLOSER_ (&processInfo.hProcess);
1257 SAFE_HANDLE_CLOSER_ (&processInfo.hThread);
1259 if (useSTDOUT != INVALID_HANDLE_VALUE) {
1260 DWORD stdoutMode = 0;
1261 Verify (::GetNamedPipeHandleState (useSTDOUT, &stdoutMode,
nullptr,
nullptr,
nullptr,
nullptr, 0));
1262 stdoutMode &= ~PIPE_NOWAIT;
1263 Verify (::SetNamedPipeHandleState (useSTDOUT, &stdoutMode,
nullptr,
nullptr));
1268 if (out !=
nullptr) {
1269 byte buf[kReadBufSize_];
1270 DWORD nBytesRead = 0;
1271 while (::ReadFile (useSTDOUT, buf,
sizeof (buf), &nBytesRead,
nullptr)) {
1272 out.
Write (span{buf, nBytesRead});
1277 if (processResult ==
nullptr) {
1278 if (processExitCode != 0) {
1291 if (processInfo.hProcess != INVALID_HANDLE_VALUE and processInfo.hProcess !=
nullptr) {
1292 (void)::TerminateProcess (processInfo.hProcess,
static_cast<UINT
> (-1));
1293 SAFE_HANDLE_CLOSER_ (&processInfo.hProcess);
1294 SAFE_HANDLE_CLOSER_ (&processInfo.hThread);
1302function<void ()> ProcessRunner::CreateRunnable_ (
Synchronized<optional<ProcessResultType>>* processResult,
1305#if USE_NOISY_TRACE_IN_THIS_MODULE_
1309 return [processResult, runningPID, progress, exe = this->fExecutable_, cmdLine = this->fArgs_, options = fOptions_, in = fStdIn_,
1310 out = fStdOut_, err = fStdErr_] () {
1311#if USE_NOISY_TRACE_IN_THIS_MODULE_
1314 auto activity =
LazyEvalActivity{[&] () {
return "executing '{}'"_f(cmdLine); }};
1316#if qStroika_Foundation_Common_Platform_POSIX
1317 Process_Runner_POSIX_ (processResult, runningPID, progress, exe, cmdLine, options, in, out, err);
1318#elif qStroika_Foundation_Common_Platform_Windows
1319 Process_Runner_Windows_ (processResult, runningPID, progress, exe, cmdLine, options, in, out, err);
#define AssertNotImplemented()
#define RequireNotNull(p)
#define AssertNotReached()
time_point< RealtimeClock, DurationSeconds > TimePointSeconds
TimePointSeconds is a simpler approach to chrono::time_point, which doesn't require using templates e...
chrono::duration< double > DurationSeconds
chrono::duration<double> - a time span (length of time) measured in seconds, but high precision.
InlineBuffer< T, BUF_SIZE > StackBuffer
Store variable sized (BUF_SIZE elements) array on the stack (.
#define Stroika_Foundation_Debug_OptionalizeTraceArgs(...)
Similar to String, but intended to more efficiently construct a String. Mutable type (String is large...
nonvirtual bool empty() const noexcept
nonvirtual String str() const
String is like std::u32string, except it is much easier to use, often much more space efficient,...
nonvirtual String LimitLength(size_t maxLen, StringShorteningPreference keepPref=StringShorteningPreference::ePreferKeepLeft) const
return the first maxLen (or fewer if string shorter) characters of this string (adding ellipsis if tr...
static String FromNarrowSDKString(const char *from)
nonvirtual SDKString AsSDKString() const
static String FromLatin1(const CHAR_T *cString)
nonvirtual bool Add(ArgByValueType< key_type > key, ArgByValueType< mapped_type > newElt, AddReplaceMode addReplaceMode=AddReplaceMode::eAddReplaces)
A generalization of a vector: a container whose elements are keyed by the natural numbers.
shared_lock< const AssertExternallySynchronizedMutex > ReadContext
Instantiate AssertExternallySynchronizedMutex::ReadContext to designate an area of code where protect...
unique_lock< AssertExternallySynchronizedMutex > WriteContext
Instantiate AssertExternallySynchronizedMutex::WriteContext to designate an area of code where protec...
nonvirtual Sequence< String > GetArguments() const
nonvirtual T As(ARGS... args) const
Exception<> is a replacement (subclass) for any std c++ exception class (e.g. the default 'std::excep...
NestedException contains a new higher level error message (typically based on argument basedOnExcepti...
nonvirtual void WaitForStarted(Time::DurationSeconds timeout=Time::kInfinity) const
wait until GetChildProcessID () returns a valid answer, or until the process failed to start (in whic...
nonvirtual optional< ProcessResultType > GetProcessResult() const
nonvirtual void PropagateIfException() const
nonvirtual void WaitForDone(Time::DurationSeconds timeout=Time::kInfinity) const
nonvirtual void Join(Time::DurationSeconds timeout=Time::kInfinity) const
Join () does WaitForDone () and throw exception if there was any error (see PropagateIfException).
nonvirtual void JoinUntil(Time::TimePointSeconds timeoutAt) const
WaitForDoneUntil () and throw exception if there was any error (see PropagateIfException).
nonvirtual void Terminate()
Run the given command, and optionally support stdin/stdout/stderr as streams (either sync with Run,...
nonvirtual void Run(const Streams::InputStream::Ptr< byte > &in, const Streams::OutputStream::Ptr< byte > &out=nullptr, const Streams::OutputStream::Ptr< byte > &error=nullptr, ProgressMonitor::Updater progress=nullptr, Time::DurationSeconds timeout=Time::kInfinity)
Run the given external command/process (set by constructor) - with the given arguments,...
nonvirtual BackgroundProcess RunInBackground(const Streams::InputStream::Ptr< byte > &in=nullptr, const Streams::OutputStream::Ptr< byte > &out=nullptr, const Streams::OutputStream::Ptr< byte > &error=nullptr, ProgressMonitor::Updater progress=nullptr)
Run the given external command/process (set by constructor) - with the given arguments in the backgro...
ProcessRunner()=delete
Construct ProcessRunner with a CommandLine to run (doesn't actually RUN til you call Run or RunInBack...
Wrap any object with Synchronized<> and it can be used similarly to the base type,...
nonvirtual T load() const
Thread::Ptr is a (unsynchronized) smart pointer referencing an internally synchronized std::thread ob...
nonvirtual void Join(Time::DurationSeconds timeout=Time::kInfinity) const
Wait for the pointed-to thread to be done. If the thread completed with an exception (other than thre...
nonvirtual void WaitForDone(Time::DurationSeconds timeout=Time::kInfinity) const
nonvirtual void JoinUntil(Time::TimePointSeconds timeoutAt) const
Wait for the pointed-to thread to be done. If the thread completed with an exception (other than thre...
Logically halfway between std::array and std::vector; Smart 'direct memory array' - which when needed...
OutputStream<>::Ptr is Smart pointer to a stream-based sink of data.
nonvirtual void Write(span< ELEMENT_TYPE2, EXTENT_2 > elts) const
Iterable<T> is a base class for containers which easily produce an Iterator<T> to traverse them.
nonvirtual RESULT_T Join(const CONVERT_TO_RESULT &convertToResult=kDefaultToStringConverter<>, const COMBINER &combiner=Characters::kDefaultStringCombiner) const
ape the JavaScript/python 'join' function - take the parts of 'this' iterable and combine them into a...
nonvirtual Iterator< T > begin() const
Support for ranged for, and STL syntax in general.
basic_string< SDKChar > SDKString
Ptr New(const function< void()> &fun2CallOnce, const optional< Characters::String > &name, const optional< Configuration > &configuration)
void Sleep(Time::Duration seconds2Wait)
void Throw(T &&e2Throw)
identical to builtin C++ 'throw' except that it does helpful, type dependent DbgTrace() messages firs...
const LazyInitialized< Containers::Sequence< filesystem::path > > kPath
void ThrowPOSIXErrNo(errno_t errNo=errno)
treats errNo as a POSIX errno value, and throws a SystemError (subclass of @std::system_error) except...
auto Handle_ErrNoResultInterruption(CALL call) -> decltype(call())
Handle UNIX EINTR system call behavior - fairly transparently - just effectively removes them from th...
auto Finally(FUNCTION &&f) -> Private_::FinallySentry< FUNCTION >
const LazyInitialized< Containers::Mapping< Characters::SDKString, Characters::SDKString > > kRawEnvironment
convert getenv() to a Mapping of SDKString (in case some issue with charactor set conversion)
optional< filesystem::path > FindExecutableInPath(const filesystem::path &fn)
If fn refers to an executable - return it (using kPATH, and kPathEXT as appropriate)
int pid_t
TODO - maybe move this to configuraiotn module???
INT_TYPE ThrowPOSIXErrNoIfNegative(INT_TYPE returnCode)
filesystem::path GetTemporary()
Ptr New(const InputStream::Ptr< byte > &src, optional< AutomaticCodeCvtFlags > codeCvtFlags={}, optional< SeekableFlag > seekable={}, ReadAhead readAhead=eReadAheadAllowed)
Create an InputStream::Ptr<Character> from the arguments (usually binary source) - which can be used ...