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"
38#include "Stroika/Foundation/Memory/Common.h"
41#include "Stroika/Foundation/Streams/MemoryStream.h"
42#include "Stroika/Foundation/Streams/TextToBinary.h"
47#include "ProcessRunner.h"
54using namespace Stroika::Foundation::Debug;
56using namespace Stroika::Foundation::Streams;
57using namespace Stroika::Foundation::Traversal;
60using Memory::MakeSharedPtr;
66#if USE_NOISY_TRACE_IN_THIS_MODULE_
70#if qStroika_Foundation_Common_Platform_POSIX
74 inline void CLOSE_ (
int& fd)
noexcept
76 if (fd >= 0) [[likely]] {
84#if qStroika_Foundation_Common_Platform_POSIX
86 static const int kMaxFD_ = [] () ->
int {
88 constexpr bool kUseSysConf_ =
true;
89#if _BSD_SOURCE || _XOPEN_SOURCE >= 500
90 [[maybe_unused]]
constexpr bool kUseGetDTableSize_ =
true;
92 [[maybe_unused]]
constexpr bool kUseGetDTableSize_ =
false;
94 constexpr bool kUseGetRLimit_ =
true;
95 if constexpr (kUseSysConf_) {
96 result = ::sysconf (_SC_OPEN_MAX);
99 else if constexpr (kUseSysConf_) {
100 result = getdtablesize ();
102 else if constexpr (kUseGetRLimit_) {
104 if (::getrlimit (RLIMIT_NOFILE, &fds) == 0) {
119 Assert (result < 4 * 1024 * 1024);
120 DbgTrace (
"::sysconf (_SC_OPEN_MAX) = {}"_f, result);
126#if qStroika_Foundation_Common_Platform_POSIX
138#if qStroika_Foundation_Common_Platform_POSIX
144 constexpr bool kUseSpawn_ =
false;
146extern char** environ;
149#if qStroika_Foundation_Common_Platform_Windows
153 AutoHANDLE_ (HANDLE h = INVALID_HANDLE_VALUE)
157 AutoHANDLE_ (
const AutoHANDLE_&) =
delete;
162 AutoHANDLE_& operator= (
const AutoHANDLE_& rhs)
166 fHandle = rhs.fHandle;
170 operator HANDLE ()
const
180 if (fHandle != INVALID_HANDLE_VALUE) {
181 Verify (::CloseHandle (fHandle));
182 fHandle = INVALID_HANDLE_VALUE;
185 void ReplaceHandleAsNonInheritable ()
187 HANDLE result = INVALID_HANDLE_VALUE;
188 Verify (::DuplicateHandle (::GetCurrentProcess (), fHandle, ::GetCurrentProcess (), &result, 0, FALSE, DUPLICATE_SAME_ACCESS));
189 Verify (::CloseHandle (fHandle));
196 inline void SAFE_HANDLE_CLOSER_ (HANDLE* h)
199 if (*h != INVALID_HANDLE_VALUE) {
200 Verify (::CloseHandle (*h));
201 *h = INVALID_HANDLE_VALUE;
208 template <Common::IAnyOf<
char,
wchar_t> CHAR_T>
209 struct String2ContigArrayCStrs_ {
210 StackBuffer<CHAR_T> fBytesBuffer;
211 StackBuffer<CHAR_T*, 10 *
sizeof (
void*)> fPtrsBuffer;
212 String2ContigArrayCStrs_ (
const Mapping<basic_string<CHAR_T>, basic_string<CHAR_T>>& data)
213 : String2ContigArrayCStrs_{data.template Map<
Iterable<basic_string<CHAR_T>>> (
214 [] (auto kvp) -> basic_string<CHAR_T> {
return kvp.fKey + SDKSTR (
"=") + kvp.fValue; })}
217 String2ContigArrayCStrs_ (
const Iterable<basic_string<CHAR_T>>& data)
219 StackBuffer<size_t> argsIdx;
220 size_t bufferIndex = 0;
221 for (
const basic_string<CHAR_T>& i : data) {
222 fBytesBuffer.push_back (span{i});
223 fBytesBuffer.push_back (
'\0');
224 argsIdx.push_back (bufferIndex);
225 bufferIndex = fBytesBuffer.GetSize ();
227 fBytesBuffer.push_back (
'\0');
228 auto freeze = fBytesBuffer.
begin ();
229 for (
size_t i : argsIdx) {
230 fPtrsBuffer.push_back (freeze + i);
232 fPtrsBuffer.push_back (
nullptr);
234 String2ContigArrayCStrs_ () =
delete;
235 String2ContigArrayCStrs_ (
const String2ContigArrayCStrs_&) =
delete;
236 String2ContigArrayCStrs_ (String2ContigArrayCStrs_&&) =
delete;
240#if qStroika_Foundation_Common_Platform_Windows
245#ifndef qUsePeekNamedPipe_
246#define qUsePeekNamedPipe_ 0
265 constexpr size_t kPipeBufSize_ = 256 * 1024;
266 constexpr size_t kReadBufSize_ = 32 * 1024;
275String ProcessRunner::Exception::mkMsg_ (
const String& errorMessage,
const optional<String>& stderrSubset,
276 const optional<ExitStatusType>& wExitStatus,
const optional<SignalID>& wTermSig)
283 extraMsg <<
"exit status {}"_f(
int (*wExitStatus));
286 if (not extraMsg.
empty ()) {
289 extraMsg <<
"terminated by signal {}"_f(
int (*wTermSig));
291 if (not extraMsg.
empty ()) {
292 sb <<
": "sv << extraMsg;
296 sb <<
" (captured stderr: "sv
297 << stderrSubset->ReplaceAll (
"\\s+"_RegEx,
" "sv).LimitLength (100, StringShorteningPreference::ePreferKeepRight) <<
")"sv;
307void ProcessRunner::ProcessResultType::ThrowIfFailed ()
309 if (fExitStatus and *fExitStatus != 0) {
312 if (fTerminatedByUncaughtSignalNumber and *fTerminatedByUncaughtSignalNumber != 0) {
313 Throw (
Exception{
"Child process failed", nullopt, nullopt, *fTerminatedByUncaughtSignalNumber});
322ProcessRunner::BackgroundProcess::BackgroundProcess ()
331 t.ThrowIfDoneWithException ();
333 if (o->fExitStatus and o->fExitStatus != ExitStatusType{}) {
336 if (o->fTerminatedByUncaughtSignalNumber) {
346 DurationSeconds remaining = timeout;
347 while (remaining > DurationSeconds{0}) {
348 if (
auto pr = GetChildProcessID ()) {
352 remaining -= DurationSeconds{1};
386 if (optional<pid_t> o = fRep_->fPID) {
387#if qStroika_Foundation_Common_Platform_POSIX
388 ::kill (SIGTERM, *o);
389#elif qStroika_Foundation_Common_Platform_Windows
391 HANDLE processHandle = ::OpenProcess (PROCESS_TERMINATE,
false, *o);
392 if (processHandle !=
nullptr) {
393 ::TerminateProcess (processHandle, 1);
394 ::CloseHandle (processHandle);
397 DbgTrace (
"::OpenProcess returned null: GetLastError () = {}"_f, GetLastError ());
424 r.
Add (i.fKey.AsSDKString (), i.fValue.AsSDKString ());
431#if qStroika_Foundation_Common_Platform_POSIX
433#elif qStroika_Foundation_Common_Platform_Windows
436 r.
Add (SDKSTR (
"PATH"), path);
450 auto activity =
LazyEvalActivity ([
this] () ->
String {
return "running '{}'"_f(this->GetCommandLine ()); });
452 if (timeout == Time::kInfinity) {
457 CreateRunnable_ (&pr,
nullptr, progress) ();
463 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { bp.Terminate (); });
465 bp.PropagateIfException ();
467 bp.GetProcessResult ().value_or (ProcessResultType{}).
ThrowIfFailed ();
473 if (timeout == Time::kInfinity) {
474 if (processResult ==
nullptr) {
475 CreateRunnable_ (
nullptr,
nullptr, progress) ();
479 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { *processResult = pr.
load (); });
480 CreateRunnable_ (&pr,
nullptr, progress) ();
484 if (processResult ==
nullptr) {
485 Thread::Ptr t =
Thread::New (CreateRunnable_ (
nullptr,
nullptr, progress), Thread::eAutoStart,
"ProcessRunner thread"_k);
490 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { *processResult = pr.
load (); });
491 Thread::Ptr t =
Thread::New (CreateRunnable_ (&pr,
nullptr, progress), Thread::eAutoStart,
"ProcessRunner thread"_k);
507 : BinaryToText::Reader::New (readFromBinStrm);
511 if (not cmdStdInValue.empty ()) {
513 : TextToBinary::Writer::New (useStdIn);
514 outStream.Write (cmdStdInValue);
516 Assert (useStdIn.GetReadOffset () == 0);
518 Run (useStdIn, useStdOut, useStdErr, progress, timeout);
521 Assert (useStdOut.GetReadOffset () == 0);
522 Assert (useStdErr.GetReadOffset () == 0);
523 return make_tuple (mkReadStream (useStdOut).ReadAll (), mkReadStream (useStdErr).ReadAll ());
526 String out = mkReadStream (useStdOut).ReadAll ();
527 String err = mkReadStream (useStdErr).ReadAll ();
528#if qStroika_Foundation_Debug_DefaultTracingOn
529 DbgTrace (
"Captured stdout: {}"_f, out);
530 DbgTrace (
"Captured stderr: {}"_f, err);
532 Throw (
Exception{e.fFailureMessage, err, e.fExitStatus, e.fTermSignal});
536 String out = mkReadStream (useStdOut).ReadAll ();
537 String err = mkReadStream (useStdErr).ReadAll ();
538#if qStroika_Foundation_Debug_DefaultTracingOn
539 DbgTrace (
"Captured stdout: {}"_f, out);
540 DbgTrace (
"Captured stderr: {}"_f, err);
542 exception_ptr e = current_exception ();
552 this->fStdOut_ = out;
553 this->fStdErr_ = error;
554 BackgroundProcess result;
555 result.fRep_->fProcessRunner =
556 Thread::New (CreateRunnable_ (&result.fRep_->fResult,
nullptr, progress), Thread::eAutoStart,
"ProcessRunner background thread"sv);
563 BackgroundProcess result;
564 result.fRep_->fProcessRunner =
565 Thread::New (CreateRunnable_ (&result.fRep_->fResult,
nullptr, progress), Thread::eAutoStart,
"ProcessRunner background thread"sv);
569#if qStroika_Foundation_Common_Platform_POSIX
572 void Process_Runner_POSIX_ (
Synchronized<optional<ProcessRunner::ProcessResultType>>* processResult,
Synchronized<optional<pid_t>>* runningPID,
577 optional<mode_t> umask = options.fChildUMask;
580 "...,cmdLine='{}',currentDir='{}',..."_f, cmdLine,
584 char trailingStderrBuf[256];
585 char* trailingStderrBufNextByte2WriteAt = begin (trailingStderrBuf);
586 size_t trailingStderrBufNWritten{};
595 int jStdin[2]{-1, -1};
596 int jStdout[2]{-1, -1};
597 int jStderr[2]{-1, -1};
598 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept {
599 ::CLOSE_ (jStdin[0]);
600 ::CLOSE_ (jStdin[1]);
601 ::CLOSE_ (jStdout[0]);
602 ::CLOSE_ (jStdout[1]);
603 ::CLOSE_ (jStderr[0]);
604 ::CLOSE_ (jStderr[1]);
610 jStdin[0] = ::open (
"/dev/null", O_RDONLY);
616 jStdout[1] = ::open (
"/dev/null", O_WRONLY);
622 jStderr[1] = ::open (
"/dev/null", O_WRONLY);
625 Assert (in ==
nullptr or (jStdin[0] >= 3 and jStdin[1] >= 3));
626 Assert (out ==
nullptr or (jStdout[0] >= 3 and jStdout[1] >= 3));
627 Assert (err ==
nullptr or (jStderr[0] >= 3 and jStderr[1] >= 3));
628 DbgTrace (
"jStdout[0-CHILD] = {} and jStdout[1-PARENT] = {}"_f, jStdout[0], jStdout[1]);
635 const char* thisEXEPath_cstr =
nullptr;
636 char** thisEXECArgv =
nullptr;
638 String2ContigArrayCStrs_<char> execDataArgs{
640 thisEXEPath_cstr = execDataArgs.fBytesBuffer.data ();
641 thisEXECArgv = execDataArgs.fPtrsBuffer.data ();
650 if (not kUseSpawn_ and thisEXEPath_cstr[0] ==
'/' and ::access (thisEXEPath_cstr, R_OK | X_OK) < 0) {
652#if USE_NOISY_TRACE_IN_THIS_MODULE_
660 posix_spawn_file_actions_t file_actions{};
667 posix_spawn_file_actions_init (&file_actions);
668 posix_spawn_file_actions_addclose (&file_actions, jStdin[0]);
669 posix_spawn_file_actions_addclose (&file_actions, jStdin[0]);
670 posix_spawn_file_actions_adddup2 (&file_actions, jStdout[1], 1);
671 posix_spawn_file_actions_addclose (&file_actions, jStdout[0]);
672 posix_spawn_file_actions_adddup2 (&file_actions, jStderr[1], 2);
673 posix_spawn_file_actions_addclose (&file_actions, jStderr[1]);
675 posix_spawnattr_t* attr =
nullptr;
676 int status = ::posix_spawnp (&childPID, thisEXEPath_cstr, &file_actions, attr, thisEXECArgv, environ);
682 childPID = DoFork_ ();
686 (void)::umask (*umask);
693 DISABLE_COMPILER_GCC_WARNING_START (
"GCC diagnostic ignored \"-Wunused-result\"")
694 (void)::chdir (useCWD.c_str ());
695 DISABLE_COMPILER_GCC_WARNING_END (
"GCC diagnostic ignored \"-Wunused-result\"")
696 if (options.fDetached.value_or (false)) {
718 int useSTDIN = jStdin[0];
719 int useSTDOUT = jStdout[1];
720 int useSTDERR = jStderr[1];
721 Assert (useSTDIN >= 0 and useSTDOUT >= 0 and useSTDERR >= 0);
725 ::dup2 (useSTDIN, 0);
726 ::dup2 (useSTDOUT, 1);
727 ::dup2 (useSTDERR, 2);
730 ::close (jStdout[0]);
731 ::close (jStdout[1]);
732 ::close (jStderr[0]);
733 ::close (jStderr[1]);
735 constexpr bool kCloseAllExtraneousFDsInChild_ =
true;
736 if (kCloseAllExtraneousFDsInChild_) {
738 for (
int i = 3; i < kMaxFD_; ++i) {
742 [[maybe_unused]]
int r = ::execvp (thisEXEPath_cstr, thisEXECArgv);
743#if USE_NOISY_TRACE_IN_THIS_MODULE_
746 myfile.open (
"/tmp/Stroika-ProcessRunner-Exec-Failed-Debug-File.txt");
747 myfile <<
"thisEXEPath_cstr = " << thisEXEPath_cstr << endl;
748 myfile <<
"r = " << r <<
" and errno = " << errno << endl;
751 ::_exit (EXIT_FAILURE);
754 ::_exit (EXIT_FAILURE);
759 Assert (childPID > 0);
761 constexpr size_t kStackBufReadAtATimeSize_ = 10 * 1024;
763#if USE_NOISY_TRACE_IN_THIS_MODULE_
764 DbgTrace (
"In Parent Fork: child process PID={}"_f, childPID);
766 if (runningPID !=
nullptr) {
767 runningPID->store (childPID);
772 int& useSTDIN = jStdin[1];
773 int& useSTDOUT = jStdout[0];
774 int& useSTDERR = jStderr[0];
783 if (useSTDIN != -1) {
786 if (useSTDOUT != -1) {
789 if (useSTDERR != -1) {
794 auto readALittleFromProcess = [&] (
int fd,
const OutputStream::Ptr<byte>& stream,
bool write2StdErrCache,
bool* eof =
nullptr,
795 bool* maybeMoreData =
nullptr) ->
void {
797 if (maybeMoreData !=
nullptr) {
798 *maybeMoreData =
false;
800 if (eof !=
nullptr) {
805 uint8_t buf[kStackBufReadAtATimeSize_];
807#if USE_NOISY_TRACE_IN_THIS_MODULE_
808 int skipedThisMany{};
810 while ((nBytesRead = ::read (fd, buf,
sizeof (buf))) > 0) {
811 Assert (nBytesRead <=
sizeof (buf));
812 if (stream !=
nullptr) {
813 stream.Write (span{buf,
static_cast<size_t> (nBytesRead)});
815 if (write2StdErrCache) {
816 for (
size_t i = 0; i < nBytesRead; ++i) {
817 Assert (&trailingStderrBuf[0] <= trailingStderrBufNextByte2WriteAt and
818 trailingStderrBufNextByte2WriteAt < end (trailingStderrBuf));
819 *trailingStderrBufNextByte2WriteAt = buf[i];
820 ++trailingStderrBufNWritten;
821 ++trailingStderrBufNextByte2WriteAt;
822 if (trailingStderrBufNextByte2WriteAt == end (trailingStderrBuf)) {
823 trailingStderrBufNextByte2WriteAt = begin (trailingStderrBuf);
825 Assert (&trailingStderrBuf[0] <= trailingStderrBufNextByte2WriteAt and
826 trailingStderrBufNextByte2WriteAt < end (trailingStderrBuf));
829#if USE_NOISY_TRACE_IN_THIS_MODULE_
830 if (errno == EAGAIN) {
832 if (skipedThisMany++ < 100) {
836 DbgTrace (
"skipped {} spamming EAGAINs"_f, skipedThisMany);
840 buf[(nBytesRead == std::size (buf)) ? (std::size (buf) - 1) : nBytesRead] =
'\0';
841 DbgTrace (
"read from process (fd={}) nBytesRead = {}: {}"_f, fd, nBytesRead,
845#if USE_NOISY_TRACE_IN_THIS_MODULE_
846 DbgTrace (
"from (fd={}) nBytesRead = {}, errno={}"_f, fd, nBytesRead, errno);
848 if (nBytesRead < 0) {
849 if (errno != EINTR and errno != EAGAIN) {
853 if (eof !=
nullptr) {
854 *eof = (nBytesRead == 0);
856 if (maybeMoreData !=
nullptr) {
857 *maybeMoreData = (nBytesRead > 0) or (nBytesRead < 0 and errno == EINTR);
861 bool maybeMoreData =
true;
862 while (maybeMoreData) {
863 readALittleFromProcess (fd, stream, write2StdErrCache,
nullptr, &maybeMoreData);
873 (void)waiter.WaitQuietly (1s);
874 readALittleFromProcess (fd, stream, write2StdErrCache, &eof);
879 byte stdinBuf[kStackBufReadAtATimeSize_];
883 if (optional<span<byte>> bytesReadFromStdIn = in.
ReadNonBlocking (span{stdinBuf})) {
884 Assert (bytesReadFromStdIn->size () <= std::size (stdinBuf));
885 if (bytesReadFromStdIn->empty ()) {
889 const byte* e = bytesReadFromStdIn->data () + bytesReadFromStdIn->size ();
890 for (
const byte* i = bytesReadFromStdIn->data (); i != e;) {
892 readSoNotBlocking (useSTDOUT, out,
false);
893 readSoNotBlocking (useSTDERR, err,
true);
895 int tmp = ::write (useSTDIN, i, e - i);
897 if (tmp < 0 and (errno == EAGAIN or errno == EWOULDBLOCK)) {
902 Assert (bytesWritten >= 0);
903 Assert (bytesWritten <= (e - i));
905 if (bytesWritten == 0) {
917 readSoNotBlocking (useSTDOUT, out,
false);
918 readSoNotBlocking (useSTDERR, err,
true);
926 readTilEOF (useSTDOUT, out,
false);
927 readTilEOF (useSTDERR, err,
true);
936 if (processResult !=
nullptr) {
939 WIFSIGNALED (status) ? WTERMSIG (status) : optional<int> ()});
941 else if (result != childPID or not WIFEXITED (status) or WEXITSTATUS (status) != 0) {
943 DbgTrace (
"childPID={}, result={}, status={}, WIFEXITED={}, WEXITSTATUS={}, WIFSIGNALED={}"_f,
static_cast<int> (childPID),
944 result, status, WIFEXITED (status), WEXITSTATUS (status), WIFSIGNALED (status));
945 if (processResult ==
nullptr) {
947 if (trailingStderrBufNWritten > std::size (trailingStderrBuf)) {
948 stderrMsg <<
"..."sv;
949 stderrMsg <<
String::FromLatin1 (Memory::ConstSpan (span{trailingStderrBufNextByte2WriteAt, end (trailingStderrBuf)}));
951 stderrMsg <<
String::FromLatin1 (Memory::ConstSpan (span{begin (trailingStderrBuf), trailingStderrBufNextByte2WriteAt}));
953 WIFEXITED (status) ? WEXITSTATUS (status) : optional<uint8_t>{},
954 WIFSIGNALED (status) ? WTERMSIG (status) : optional<uint8_t>{}});
962#if qStroika_Foundation_Common_Platform_Windows
964 void Process_Runner_Windows_ (
Synchronized<optional<ProcessRunner::ProcessResultType>>* processResult,
966 const optional<filesystem::path>& executable,
const CommandLine& cmdLine,
const ProcessRunner::Options& options,
971 "...,cmdLine='{}',currentDir={},..."_f, cmdLine,
984 AutoHANDLE_ jStdin[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
985 AutoHANDLE_ jStdout[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
986 AutoHANDLE_ jStderr[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
988 PROCESS_INFORMATION processInfo{};
989 processInfo.hProcess = INVALID_HANDLE_VALUE;
990 processInfo.hThread = INVALID_HANDLE_VALUE;
994 SECURITY_DESCRIPTOR sd{};
995 Verify (::InitializeSecurityDescriptor (&sd, SECURITY_DESCRIPTOR_REVISION));
996 Verify (::SetSecurityDescriptorDacl (&sd,
true, 0,
false));
997 SECURITY_ATTRIBUTES sa = {
sizeof (SECURITY_ATTRIBUTES), &sd,
true};
999 Verify (::CreatePipe (&jStdin[1], &jStdin[0], &sa, kPipeBufSize_));
1002 Verify (::CreatePipe (&jStdout[1], &jStdout[0], &sa, kPipeBufSize_));
1005 Verify (::CreatePipe (&jStderr[1], &jStderr[0], &sa, kPipeBufSize_));
1012 jStdin[0].ReplaceHandleAsNonInheritable ();
1015 jStdout[1].ReplaceHandleAsNonInheritable ();
1018 jStderr[1].ReplaceHandleAsNonInheritable ();
1022 STARTUPINFO startInfo{};
1023 startInfo.cb =
sizeof (startInfo);
1024 startInfo.hStdInput = jStdin[1];
1025 startInfo.hStdOutput = jStdout[0];
1026 startInfo.hStdError = jStderr[0];
1027 startInfo.dwFlags |= STARTF_USESTDHANDLES;
1029 DWORD createProcFlags{NORMAL_PRIORITY_CLASS};
1030 if (options.fCreateNoWindow) {
1031 createProcFlags |= CREATE_NO_WINDOW;
1033 else if (options.fDetached.value_or (
false)) {
1035 createProcFlags |= DETACHED_PROCESS;
1041 bool bInheritHandles =
true;
1043 TCHAR cmdLineBuf[32768];
1044 Characters::CString::Copy (cmdLineBuf, std::size (cmdLineBuf), cmdLine.
As<
String> ().
AsSDKString ().c_str ());
1046 optional<filesystem::path> useEXEPath = executable;
1049#if qStroika_Foundation_Debug_AssertionsChecked
1052 DbgTrace (
"Warning: Cannot find exe '{}' in PATH ({})"_f, useEXEPath,
kPath ());
1058 if (cmdArgs.size () >= 1) {
1059 filesystem::path exe2Find = cmdArgs[0].As<filesystem::path> ();
1061 DbgTrace (
"Warning: Cannot find exe '{}' in PATH ({})"_f, exe2Find,
kPath ());
1067 unique_ptr<String2ContigArrayCStrs_<SDKChar>> envBuffer;
1068 LPVOID lpEnvironment =
nullptr;
1069 if (options.fEnvironment) {
1071 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*oep));
1074 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*om));
1077 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*oms));
1080 lpEnvironment = envBuffer->fBytesBuffer.data ();
1081 if constexpr (same_as<SDKChar, wchar_t>) {
1082 createProcFlags |= CREATE_UNICODE_ENVIRONMENT;
1090 ::CreateProcess (useEXEPath == nullopt ?
nullptr : useEXEPath->c_str (), cmdLineBuf, nullptr, nullptr, bInheritHandles,
1091 createProcFlags, lpEnvironment, useCWD.c_str (), &startInfo, &processInfo));
1094 if (runningPID !=
nullptr) {
1095 runningPID->store (processInfo.dwProcessId);
1103 jStdout[0].Close ();
1104 jStderr[0].Close ();
1107 AutoHANDLE_& useSTDIN = jStdin[0];
1108 Assert (jStdin[1] == INVALID_HANDLE_VALUE);
1109 AutoHANDLE_& useSTDOUT = jStdout[1];
1110 Assert (jStdout[0] == INVALID_HANDLE_VALUE);
1111 AutoHANDLE_& useSTDERR = jStderr[1];
1112 Assert (jStderr[0] == INVALID_HANDLE_VALUE);
1114 constexpr size_t kStackBufReadAtATimeSize_ = 10 * 1024;
1117 if (p == INVALID_HANDLE_VALUE) {
1120 byte buf[kReadBufSize_];
1121#if qUsePeekNamedPipe_
1122 DWORD nBytesAvail{};
1128#
if qUsePeekNamedPipe_
1129 ::PeekNamedPipe (p,
nullptr,
nullptr,
nullptr, &nBytesAvail,
nullptr) and nBytesAvail != 0 and
1131 ::ReadFile (p, buf,
sizeof (buf), &nBytesRead,
nullptr) and nBytesRead > 0) {
1133 o.Write (span{buf, nBytesRead});
1135#if USE_NOISY_TRACE_IN_THIS_MODULE_
1136 buf[(nBytesRead == std::size (buf)) ? (std::size (buf) - 1) : nBytesRead] = byte{
'\0'};
1137 DbgTrace (
"read from process (fd={}) nBytesRead = {}: {}"_f, p, nBytesRead, buf);
1142 if (processInfo.hProcess != INVALID_HANDLE_VALUE) {
1148 auto mkPipeNoWait_ = [] (HANDLE ioHandle) ->
void {
1149 if (ioHandle != INVALID_HANDLE_VALUE) {
1151 Verify (::GetNamedPipeHandleState (ioHandle, &mode,
nullptr,
nullptr,
nullptr,
nullptr, 0));
1152 mode |= PIPE_NOWAIT;
1153 Verify (::SetNamedPipeHandleState (ioHandle, &mode,
nullptr,
nullptr));
1156 mkPipeNoWait_ (useSTDIN);
1157 mkPipeNoWait_ (useSTDOUT);
1158 mkPipeNoWait_ (useSTDERR);
1164 if (in !=
nullptr) {
1165 byte stdinBuf[kStackBufReadAtATimeSize_];
1167 while (
size_t nbytes = in.
ReadBlocking (span{stdinBuf}).size ()) {
1168 Assert (nbytes <= std::size (stdinBuf));
1169 const byte* p = begin (stdinBuf);
1170 const byte* e = p + nbytes;
1173 if (::WriteFile (useSTDIN, p, Math::PinToMaxForType<DWORD> (e - p), &written,
nullptr) == 0) {
1174 DWORD lastErr = ::GetLastError ();
1180 if (lastErr != ERROR_SUCCESS and lastErr != ERROR_NO_MORE_FILES and lastErr != ERROR_PIPE_BUSY and
1181 lastErr != ERROR_NO_DATA) {
1182 DbgTrace (
"in RunExternalProcess_ - throwing {} while fill in stdin"_f, lastErr);
1183 ThrowSystemErrNo (lastErr);
1186 Assert (written <=
static_cast<size_t> (e - p));
1190 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1191 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1193 if (p < e and written == 0) {
1200 if (Time::GetTickCount () > timeoutAt) {
1201 DbgTrace (_T (
"process timed out (writing initial data) - so throwing up!"));
1203 (void)::TerminateProcess (processInfo.hProcess, -1);
1204 Throw (Execution::Platform::Windows::Exception (ERROR_TIMEOUT));
1219 int timesWaited = 0;
1228 HANDLE events[1] = {processInfo.hProcess};
1235 double remainingTimeout = (timesWaited <= 5) ? 0.1 : 0.5;
1236 DWORD waitResult = ::WaitForMultipleObjects (
static_cast<DWORD
> (std::size (events)), events,
false,
1237 static_cast<int> (remainingTimeout * 1000));
1240 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1241 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1242 switch (waitResult) {
1243 case WAIT_OBJECT_0: {
1244 DbgTrace (
"external process finished (DONE)"_f);
1246 goto DoneWithProcess;
1248 case WAIT_TIMEOUT: {
1249 DbgTrace (
"still waiting for external process output (WAIT_TIMEOUT)"_f);
1255 DWORD processExitCode{};
1256 Verify (::GetExitCodeProcess (processInfo.hProcess, &processExitCode));
1258 SAFE_HANDLE_CLOSER_ (&processInfo.hProcess);
1259 SAFE_HANDLE_CLOSER_ (&processInfo.hThread);
1261 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1262 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1264 if (processResult ==
nullptr) {
1265 if (processExitCode != 0) {
1276 if (processInfo.hProcess != INVALID_HANDLE_VALUE and processInfo.hProcess !=
nullptr) {
1277 (void)::TerminateProcess (processInfo.hProcess,
static_cast<UINT
> (-1));
1278 SAFE_HANDLE_CLOSER_ (&processInfo.hProcess);
1279 SAFE_HANDLE_CLOSER_ (&processInfo.hThread);
1287function<void ()> ProcessRunner::CreateRunnable_ (
Synchronized<optional<ProcessResultType>>* processResult,
1290#if USE_NOISY_TRACE_IN_THIS_MODULE_
1294 return [processResult, runningPID, progress, exe = this->fExecutable_, cmdLine = this->fArgs_, options = fOptions_, in = fStdIn_,
1295 out = fStdOut_, err = fStdErr_] () {
1296#if USE_NOISY_TRACE_IN_THIS_MODULE_
1299 auto activity =
LazyEvalActivity{[&] () {
return "executing '{}'"_f(cmdLine); }};
1301#if qStroika_Foundation_Common_Platform_POSIX
1302 Process_Runner_POSIX_ (processResult, runningPID, progress, exe, cmdLine, options, in, out, err);
1303#elif qStroika_Foundation_Common_Platform_Windows
1304 Process_Runner_Windows_ (processResult, runningPID, progress, exe, cmdLine, options, in, out, err);
#define AssertNotImplemented()
#define RequireNotNull(p)
#define AssertNotReached()
auto MakeSharedPtr(ARGS_TYPE &&... args) -> shared_ptr< T >
same as make_shared, but if type T has block allocation, then use block allocation for the 'shared pa...
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.
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
EXPECTED::value_type ThrowIfFailed(const EXPECTED &e)
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 ...
Ptr New(const Streams::OutputStream::Ptr< byte > &src, const Characters::CodeCvt<> &char2OutputConverter)