4#include "Stroika/Foundation/StroikaPreComp.h"
8#if qStroika_Foundation_Common_Platform_POSIX
11#include <sys/resource.h>
17#if qStroika_Foundation_Common_Platform_MacOS
26#include "Stroika/Foundation/Containers/Sequence.h"
28#if qStroika_Foundation_Common_Platform_Windows
29#include "Stroika/Foundation/Execution/Platform/Windows/Exception.h"
31#include "Stroika/Foundation/Execution/Activity.h"
32#include "Stroika/Foundation/Execution/CommandLine.h"
33#include "Stroika/Foundation/Execution/Exceptions.h"
35#include "Stroika/Foundation/Execution/Module.h"
40#include "Stroika/Foundation/IO/FileSystem/FileUtils.h"
43#include "Stroika/Foundation/Memory/Common.h"
46#include "Stroika/Foundation/Streams/MemoryStream.h"
47#include "Stroika/Foundation/Streams/TextToBinary.h"
49#include "ProcessRunner.h"
56using namespace Stroika::Foundation::Debug;
58using namespace Stroika::Foundation::Streams;
59using namespace Stroika::Foundation::Traversal;
62using Memory::MakeSharedPtr;
68#if USE_NOISY_TRACE_IN_THIS_MODULE_
72#if qStroika_Foundation_Common_Platform_POSIX
76 inline void CLOSE_ (
int& fd)
noexcept
78 if (fd >= 0) [[likely]] {
86#if qStroika_Foundation_Common_Platform_POSIX
98#if qStroika_Foundation_Common_Platform_POSIX
104 constexpr bool kUseSpawn_ =
false;
106extern char** environ;
109#if qStroika_Foundation_Common_Platform_Windows
113 AutoHANDLE_ (HANDLE h = INVALID_HANDLE_VALUE)
117 AutoHANDLE_ (
const AutoHANDLE_&) =
delete;
122 AutoHANDLE_& operator= (
const AutoHANDLE_& rhs)
126 fHandle = rhs.fHandle;
130 operator HANDLE ()
const
140 if (fHandle != INVALID_HANDLE_VALUE) {
141 Verify (::CloseHandle (fHandle));
142 fHandle = INVALID_HANDLE_VALUE;
145 void ReplaceHandleAsNonInheritable ()
147 HANDLE result = INVALID_HANDLE_VALUE;
148 Verify (::DuplicateHandle (::GetCurrentProcess (), fHandle, ::GetCurrentProcess (), &result, 0, FALSE, DUPLICATE_SAME_ACCESS));
149 Verify (::CloseHandle (fHandle));
156 inline void SAFE_HANDLE_CLOSER_ (HANDLE* h)
159 if (*h != INVALID_HANDLE_VALUE) {
160 Verify (::CloseHandle (*h));
161 *h = INVALID_HANDLE_VALUE;
168 template <Common::IAnyOf<
char,
wchar_t> CHAR_T>
169 struct String2ContigArrayCStrs_ {
170 StackBuffer<CHAR_T> fBytesBuffer;
171 StackBuffer<CHAR_T*, 10 *
sizeof (
void*)> fPtrsBuffer;
172 String2ContigArrayCStrs_ (
const Mapping<basic_string<CHAR_T>, basic_string<CHAR_T>>& data)
173 : String2ContigArrayCStrs_{data.template Map<
Iterable<basic_string<CHAR_T>>> (
174 [] (auto kvp) -> basic_string<CHAR_T> {
return kvp.fKey + SDKSTR (
"=") + kvp.fValue; })}
177 String2ContigArrayCStrs_ (
const Iterable<basic_string<CHAR_T>>& data)
179 StackBuffer<size_t> argsIdx;
180 size_t bufferIndex = 0;
181 for (
const basic_string<CHAR_T>& i : data) {
182 fBytesBuffer.push_back (span{i});
183 fBytesBuffer.push_back (
'\0');
184 argsIdx.push_back (bufferIndex);
185 bufferIndex = fBytesBuffer.GetSize ();
187 fBytesBuffer.push_back (
'\0');
188 auto freeze = fBytesBuffer.
begin ();
189 for (
size_t i : argsIdx) {
190 fPtrsBuffer.push_back (freeze + i);
192 fPtrsBuffer.push_back (
nullptr);
194 String2ContigArrayCStrs_ () =
delete;
195 String2ContigArrayCStrs_ (
const String2ContigArrayCStrs_&) =
delete;
196 String2ContigArrayCStrs_ (String2ContigArrayCStrs_&&) =
delete;
200#if qStroika_Foundation_Common_Platform_Windows
205#ifndef qUsePeekNamedPipe_
206#define qUsePeekNamedPipe_ 0
225 constexpr size_t kPipeBufSize_ = 256 * 1024;
226 constexpr size_t kReadBufSize_ = 32 * 1024;
235String ProcessRunner::Exception::mkMsg_ (
const String& errorMessage,
const optional<String>& stderrSubset,
236 const optional<ExitStatusType>& wExitStatus,
const optional<SignalID>& wTermSig)
256 sb <<
" (captured stderr: "sv
257 <<
stderrSubset->ReplaceAll (
"\\s+"_RegEx,
" "sv).LimitLength (100, StringShorteningPreference::ePreferKeepRight) <<
")"sv;
267void ProcessRunner::ProcessResultType::ThrowIfFailed ()
269 if (fExitStatus and *fExitStatus != 0) {
270 Throw (
Exception{
"Child process failed"sv, nullopt, *fExitStatus});
272 if (fTerminatedByUncaughtSignalNumber and *fTerminatedByUncaughtSignalNumber != 0) {
273 Throw (
Exception{
"Child process failed"sv, nullopt, nullopt, *fTerminatedByUncaughtSignalNumber});
282 sb <<
"exitStatus: "sv << fExitStatus;
284 if (fTerminatedByUncaughtSignalNumber) {
288 sb <<
"terminatedByUncaughtSignalNumber: "sv << fTerminatedByUncaughtSignalNumber;
299ProcessRunner::BackgroundProcess::BackgroundProcess ()
300 : fRep_{MakeSharedPtr<Rep_> ()}
309 if (
auto o = GetProcessResult ()) {
310 if (o->fExitStatus and o->fExitStatus != ExitStatusType{}) {
313 if (o->fTerminatedByUncaughtSignalNumber) {
324 if (
auto pr = GetChildProcessID ()) {
328 }
while (runUntil > Time::GetTickCount ());
362 if (optional<pid_t> o = fRep_->fDetailedRunnableRep_->fRunningPID.load ()) {
363#if qStroika_Foundation_Common_Platform_POSIX
364 ::kill (SIGTERM, *o);
365#elif qStroika_Foundation_Common_Platform_Windows
367 HANDLE processHandle = ::OpenProcess (PROCESS_TERMINATE,
false, *o);
368 if (processHandle !=
nullptr) {
369 ::TerminateProcess (processHandle, 1);
370 ::CloseHandle (processHandle);
373 DbgTrace (
"::OpenProcess returned null: GetLastError () = {}"_f, GetLastError ());
384 if (fRep_ and fRep_->fDetailedRunnableRep_) {
385 sb <<
"processID: "sv << fRep_->fDetailedRunnableRep_->fRunningPID.load ();
386 sb <<
", processResult: "sv << fRep_->fDetailedRunnableRep_->fProcessResult.load ();
411 r.
Add (i.fKey.AsSDKString (), i.fValue.AsSDKString ());
418#if qStroika_Foundation_Common_Platform_POSIX
420#elif qStroika_Foundation_Common_Platform_Windows
423 r.
Add (SDKSTR (
"PATH"), path);
437 Require (not fOptions_.fDetached);
438 auto activity =
LazyEvalActivity ([
this] () ->
String {
return "running '{}'"_f(this->GetCommandLine ()); });
440 if (timeout == Time::kInfinity) {
444 auto [runable, results] = CreateDetailedRunnable_ ();
446 results->fProcessResult.load ().value_or (ProcessResultType{}).
ThrowIfFailed ();
451 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { bp.Terminate (); });
453 bp.PropagateIfException ();
455 bp.GetProcessResult ().value_or (ProcessResultType{}).
ThrowIfFailed ();
462 if (timeout == Time::kInfinity) {
463 if (processResult ==
nullptr) {
464 CreateSimpleRunnable_ () ();
467 auto [runnable, prDetails] = CreateDetailedRunnable_ ();
468#if qCompilerAndStdLib_NamedAutoLocalBindingNotCapturable_Buggy
469 auto pd2 = prDetails;
470 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { *processResult = pd2->fProcessResult.load (); });
472 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { *processResult = prDetails->fProcessResult.load (); });
478 if (processResult ==
nullptr) {
483 auto [runnable, prDetails] = CreateDetailedRunnable_ ();
484#if qCompilerAndStdLib_NamedAutoLocalBindingNotCapturable_Buggy
485 auto pd2 = prDetails;
486 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { *processResult = pd2->fProcessResult.load (); });
488 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept { *processResult = prDetails->fProcessResult.load (); });
505 : BinaryToText::Reader::New (readFromBinStrm);
509 if (not cmdStdInValue.empty ()) {
511 : TextToBinary::Writer::New (useStdIn);
512 outStream.Write (cmdStdInValue);
514 Assert (useStdIn.GetReadOffset () == 0);
516 Run (useStdIn, useStdOut, useStdErr, 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 ();
549 if (fOptions_.fDetached) {
550 Require (in ==
nullptr and out ==
nullptr and error ==
nullptr);
553 this->fStdOut_ = out;
554 this->fStdErr_ = error;
555 BackgroundProcess result;
556 auto [runnable, prDetails] = CreateDetailedRunnable_ ();
557 result.fRep_->fDetailedRunnableRep_ = prDetails;
558 if (fOptions_.fDetached) {
562 result.fRep_->fProcessRunner =
Thread::New (runnable, Thread::eAutoStart,
"ProcessRunner background thread"sv);
570 BackgroundProcess result;
571 auto [runnable, prDetails] = CreateDetailedRunnable_ ();
572 result.fRep_->fDetailedRunnableRep_ = prDetails;
573 if (fOptions_.fDetached) {
577 result.fRep_->fProcessRunner =
Thread::New (runnable, Thread::eAutoStart,
"ProcessRunner background thread"sv);
597 return Run (in, out, error, timeout);
599[[deprecated (
"Since Stroika v3.0d23d")]] tuple<Characters::String, Characters::String>
604 return Run (cmdStdInValue, stringOpts, timeout);
607#if qStroika_Foundation_Common_Platform_MacOS
609 void closefrom_ (
int lowfd)
611 DIR* dir = ::opendir (
"/dev/fd");
612 if (dir ==
nullptr) {
614 int maxFD = ::getdtablesize ();
615 for (
int i = lowfd; i < maxFD; i++) {
620 for (
struct dirent* entry; (entry = ::readdir (dir)) !=
nullptr;) {
621 char* endptr =
nullptr;
622 long fd = ::strtol (entry->d_name, &endptr, 10);
624 if (*endptr ==
'\0' and fd >= lowfd and fd != ::dirfd (dir)) {
625 ::close (
static_cast<int> (fd));
633#if qStroika_Foundation_Common_Platform_POSIX
635void ProcessRunner::Process_Runner_POSIX_ (
const shared_ptr<DetailedRunnableRep_>& runneeDetails,
636 [[maybe_unused]]
const optional<filesystem::path>& executable,
const CommandLine& cmdLine,
640 optional<mode_t> umask = options.fChildUMask;
643 "...,cmdLine='{}',currentDir='{}',..."_f, cmdLine,
647 char trailingStderrBuf[256];
648 char* trailingStderrBufNextByte2WriteAt = begin (trailingStderrBuf);
649 size_t trailingStderrBufNWritten{};
658 int jStdin[2]{-1, -1};
659 int jStdout[2]{-1, -1};
660 int jStderr[2]{-1, -1};
661 [[maybe_unused]]
auto&& cleanup =
Finally ([&] ()
noexcept {
662 ::CLOSE_ (jStdin[0]);
663 ::CLOSE_ (jStdin[1]);
664 ::CLOSE_ (jStdout[0]);
665 ::CLOSE_ (jStdout[1]);
666 ::CLOSE_ (jStderr[0]);
667 ::CLOSE_ (jStderr[1]);
673 jStdin[0] = ::open (
"/dev/null", O_RDONLY);
679 jStdout[1] = ::open (
"/dev/null", O_WRONLY);
685 jStderr[1] = ::open (
"/dev/null", O_WRONLY);
688 Assert (in ==
nullptr or (jStdin[0] >= 3 and jStdin[1] >= 3));
689 Assert (out ==
nullptr or (jStdout[0] >= 3 and jStdout[1] >= 3));
690 Assert (err ==
nullptr or (jStderr[0] >= 3 and jStderr[1] >= 3));
691 DbgTrace (
"jStdout[0-CHILD] = {} and jStdout[1-PARENT] = {}"_f, jStdout[0], jStdout[1]);
698 const char* thisEXEPath_cstr =
nullptr;
699 char** thisEXECArgv =
nullptr;
701 String2ContigArrayCStrs_<char> execDataArgs{
703 thisEXEPath_cstr = execDataArgs.fBytesBuffer.data ();
704 thisEXECArgv = execDataArgs.fPtrsBuffer.data ();
713 if (not kUseSpawn_ and thisEXEPath_cstr[0] ==
'/' and ::access (thisEXEPath_cstr, R_OK | X_OK) < 0) {
715#if USE_NOISY_TRACE_IN_THIS_MODULE_
723 posix_spawn_file_actions_t file_actions{};
730 posix_spawn_file_actions_init (&file_actions);
731 posix_spawn_file_actions_addclose (&file_actions, jStdin[0]);
732 posix_spawn_file_actions_addclose (&file_actions, jStdin[0]);
733 posix_spawn_file_actions_adddup2 (&file_actions, jStdout[1], 1);
734 posix_spawn_file_actions_addclose (&file_actions, jStdout[0]);
735 posix_spawn_file_actions_adddup2 (&file_actions, jStderr[1], 2);
736 posix_spawn_file_actions_addclose (&file_actions, jStderr[1]);
738 posix_spawnattr_t* attr =
nullptr;
739 int status = ::posix_spawnp (&childPID, thisEXEPath_cstr, &file_actions, attr, thisEXECArgv, environ);
745 childPID = DoFork_ ();
749 (void)::umask (*umask);
756 DISABLE_COMPILER_GCC_WARNING_START (
"GCC diagnostic ignored \"-Wunused-result\"")
757 (void)::chdir (useCWD.c_str ());
758 DISABLE_COMPILER_GCC_WARNING_END (
"GCC diagnostic ignored \"-Wunused-result\"")
759 if (options.fDetached) {
781 int useSTDIN = jStdin[0];
782 int useSTDOUT = jStdout[1];
783 int useSTDERR = jStderr[1];
784 Assert (useSTDIN >= 0 and useSTDOUT >= 0 and useSTDERR >= 0);
788 ::dup2 (useSTDIN, 0);
789 ::dup2 (useSTDOUT, 1);
790 ::dup2 (useSTDERR, 2);
793 ::close (jStdout[0]);
794 ::close (jStdout[1]);
795 ::close (jStderr[0]);
796 ::close (jStderr[1]);
798 constexpr bool kCloseAllExtraneousFDsInChild_ =
true;
799 if (kCloseAllExtraneousFDsInChild_) {
801#if qStroika_Foundation_Common_Platform_MacOS
807 [[maybe_unused]]
int r = ::execvp (thisEXEPath_cstr, thisEXECArgv);
808#if USE_NOISY_TRACE_IN_THIS_MODULE_
811 myfile.open (
"/tmp/Stroika-ProcessRunner-Exec-Failed-Debug-File.txt");
812 myfile <<
"thisEXEPath_cstr = " << thisEXEPath_cstr << endl;
813 myfile <<
"r = " << r <<
" and errno = " << errno << endl;
816 ::_exit (EXIT_FAILURE);
819 ::_exit (EXIT_FAILURE);
824 Assert (childPID > 0);
826 constexpr size_t kStackBufReadAtATimeSize_ = 10 * 1024;
828#if USE_NOISY_TRACE_IN_THIS_MODULE_
829 DbgTrace (
"In Parent Fork: child process PID={}"_f, childPID);
831 if (runneeDetails !=
nullptr) {
832 runneeDetails->fRunningPID.store (childPID);
837 int& useSTDIN = jStdin[1];
838 int& useSTDOUT = jStdout[0];
839 int& useSTDERR = jStderr[0];
848 if (useSTDIN != -1) {
851 if (useSTDOUT != -1) {
854 if (useSTDERR != -1) {
859 auto readALittleFromProcess = [&] (
int fd,
const OutputStream::Ptr<byte>& stream,
bool write2StdErrCache,
bool* eof =
nullptr,
860 bool* maybeMoreData =
nullptr) ->
void {
862 if (maybeMoreData !=
nullptr) {
863 *maybeMoreData =
false;
865 if (eof !=
nullptr) {
870 uint8_t buf[kStackBufReadAtATimeSize_];
872#if USE_NOISY_TRACE_IN_THIS_MODULE_
873 int skipedThisMany{};
875 while ((nBytesRead = ::read (fd, buf,
sizeof (buf))) > 0) {
876 Assert (nBytesRead <=
sizeof (buf));
877 if (stream !=
nullptr) {
878 stream.Write (span{buf,
static_cast<size_t> (nBytesRead)});
880 if (write2StdErrCache) {
881 for (
size_t i = 0; i < nBytesRead; ++i) {
882 Assert (&trailingStderrBuf[0] <= trailingStderrBufNextByte2WriteAt and trailingStderrBufNextByte2WriteAt < end (trailingStderrBuf));
883 *trailingStderrBufNextByte2WriteAt = buf[i];
884 ++trailingStderrBufNWritten;
885 ++trailingStderrBufNextByte2WriteAt;
886 if (trailingStderrBufNextByte2WriteAt == end (trailingStderrBuf)) {
887 trailingStderrBufNextByte2WriteAt = begin (trailingStderrBuf);
889 Assert (&trailingStderrBuf[0] <= trailingStderrBufNextByte2WriteAt and trailingStderrBufNextByte2WriteAt < end (trailingStderrBuf));
892#if USE_NOISY_TRACE_IN_THIS_MODULE_
893 if (errno == EAGAIN) {
895 if (skipedThisMany++ < 100) {
899 DbgTrace (
"skipped {} spamming EAGAINs"_f, skipedThisMany);
903 buf[(nBytesRead == std::size (buf)) ? (std::size (buf) - 1) : nBytesRead] =
'\0';
904 DbgTrace (
"read from process (fd={}) nBytesRead = {}: {}"_f, fd, nBytesRead,
908#if USE_NOISY_TRACE_IN_THIS_MODULE_
909 DbgTrace (
"from (fd={}) nBytesRead = {}, errno={}"_f, fd, nBytesRead, errno);
911 if (nBytesRead < 0) {
912 if (errno != EINTR and errno != EAGAIN) {
916 if (eof !=
nullptr) {
917 *eof = (nBytesRead == 0);
919 if (maybeMoreData !=
nullptr) {
920 *maybeMoreData = (nBytesRead > 0) or (nBytesRead < 0 and errno == EINTR);
924 bool maybeMoreData =
true;
925 while (maybeMoreData) {
926 readALittleFromProcess (fd, stream, write2StdErrCache,
nullptr, &maybeMoreData);
936 (void)waiter.WaitQuietly (1s);
937 readALittleFromProcess (fd, stream, write2StdErrCache, &eof);
941 if (options.fDetached) {
942 Assert (in ==
nullptr and useSTDOUT == -1 and useSTDERR == -1);
946 byte stdinBuf[kStackBufReadAtATimeSize_];
950 if (optional<span<byte>> bytesReadFromStdIn = in.
ReadNonBlocking (span{stdinBuf})) {
951 Assert (bytesReadFromStdIn->size () <= std::size (stdinBuf));
952 if (bytesReadFromStdIn->empty ()) {
956 const byte* e = bytesReadFromStdIn->data () + bytesReadFromStdIn->size ();
957 for (
const byte* i = bytesReadFromStdIn->data (); i != e;) {
959 readSoNotBlocking (useSTDOUT, out,
false);
960 readSoNotBlocking (useSTDERR, err,
true);
962 int tmp = ::write (useSTDIN, i, e - i);
964 if (tmp < 0 and (errno == EAGAIN or errno == EWOULDBLOCK)) {
969 Assert (bytesWritten >= 0);
970 Assert (bytesWritten <= (e - i));
972 if (bytesWritten == 0) {
984 readSoNotBlocking (useSTDOUT, out,
false);
985 readSoNotBlocking (useSTDERR, err,
true);
993 readTilEOF (useSTDOUT, out,
false);
994 readTilEOF (useSTDERR, err,
true);
997 if (not options.fDetached) {
1004 if (runneeDetails !=
nullptr) {
1007 WIFEXITED (status) ? WEXITSTATUS (status) : optional<int>{}, WIFSIGNALED (status) ? WTERMSIG (status) : optional<int>{}});
1009 else if (result != childPID or not WIFEXITED (status) or WEXITSTATUS (status) != 0) {
1011 DbgTrace (
"childPID={}, result={}, status={}, WIFEXITED={}, WEXITSTATUS={}, WIFSIGNALED={}"_f,
static_cast<int> (childPID),
1012 result, status, WIFEXITED (status), WEXITSTATUS (status), WIFSIGNALED (status));
1014 if (trailingStderrBufNWritten > std::size (trailingStderrBuf)) {
1015 stderrMsg <<
"..."sv;
1016 stderrMsg <<
String::FromLatin1 (Memory::ConstSpan (span{trailingStderrBufNextByte2WriteAt, end (trailingStderrBuf)}));
1018 stderrMsg <<
String::FromLatin1 (Memory::ConstSpan (span{begin (trailingStderrBuf), trailingStderrBufNextByte2WriteAt}));
1020 WIFSIGNALED (status) ? WTERMSIG (status) : optional<uint8_t>{}});
1027#if qStroika_Foundation_Common_Platform_Windows
1028void ProcessRunner::Process_Runner_Windows_ (
const shared_ptr<DetailedRunnableRep_>& runneeDetails,
const optional<filesystem::path>& executable,
1034 "...,cmdLine='{}',currentDir={},..."_f, cmdLine,
1035 String{useCWD}.
LimitLength (50, StringShorteningPreference::ePreferKeepRight))};
1047 AutoHANDLE_ jStdin[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
1048 AutoHANDLE_ jStdout[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
1049 AutoHANDLE_ jStderr[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
1051 PROCESS_INFORMATION processInfo{};
1052 processInfo.hProcess = INVALID_HANDLE_VALUE;
1053 processInfo.hThread = INVALID_HANDLE_VALUE;
1057 SECURITY_DESCRIPTOR sd{};
1058 Verify (::InitializeSecurityDescriptor (&sd, SECURITY_DESCRIPTOR_REVISION));
1059 Verify (::SetSecurityDescriptorDacl (&sd,
true, 0,
false));
1060 SECURITY_ATTRIBUTES sa = {
sizeof (SECURITY_ATTRIBUTES), &sd,
true};
1062 Verify (::CreatePipe (&jStdin[1], &jStdin[0], &sa, kPipeBufSize_));
1065 Verify (::CreatePipe (&jStdout[1], &jStdout[0], &sa, kPipeBufSize_));
1068 Verify (::CreatePipe (&jStderr[1], &jStderr[0], &sa, kPipeBufSize_));
1075 jStdin[0].ReplaceHandleAsNonInheritable ();
1078 jStdout[1].ReplaceHandleAsNonInheritable ();
1081 jStderr[1].ReplaceHandleAsNonInheritable ();
1085 STARTUPINFO startInfo{
1086 .cb =
sizeof (startInfo), .dwFlags = STARTF_USESTDHANDLES, .hStdInput = jStdin[1], .hStdOutput = jStdout[0], .hStdError = jStderr[0]};
1088 DWORD createProcFlags{NORMAL_PRIORITY_CLASS};
1089 if (options.fCreateNoWindow) {
1090 createProcFlags |= CREATE_NO_WINDOW;
1092 else if (options.fDetached) {
1094 createProcFlags |= DETACHED_PROCESS;
1100 bool bInheritHandles =
true;
1102 TCHAR cmdLineBuf[32768];
1103 Characters::CString::Copy (cmdLineBuf, std::size (cmdLineBuf), cmdLine.
As<
String> ().
AsSDKString ().c_str ());
1105 optional<filesystem::path> useEXEPath = executable;
1108#if qStroika_Foundation_Debug_AssertionsChecked
1111 DbgTrace (
"Warning: Cannot find exe '{}' in PATH ({})"_f, useEXEPath,
kPath ());
1117 if (cmdArgs.size () >= 1) {
1118 filesystem::path exe2Find = cmdArgs[0].As<filesystem::path> ();
1120 DbgTrace (
"Warning: Cannot find exe '{}' in PATH ({})"_f, exe2Find,
kPath ());
1126 unique_ptr<String2ContigArrayCStrs_<SDKChar>> envBuffer;
1127 LPVOID lpEnvironment =
nullptr;
1128 if (options.fEnvironment) {
1130 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*oep));
1133 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*om));
1136 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*oms));
1139 lpEnvironment = envBuffer->fBytesBuffer.data ();
1140 if constexpr (same_as<SDKChar, wchar_t>) {
1141 createProcFlags |= CREATE_UNICODE_ENVIRONMENT;
1149 ::CreateProcess (useEXEPath == nullopt ?
nullptr : useEXEPath->c_str (), cmdLineBuf, nullptr, nullptr, bInheritHandles,
1150 createProcFlags, lpEnvironment, useCWD.c_str (), &startInfo, &processInfo));
1153 if (runneeDetails !=
nullptr) {
1154 runneeDetails->fRunningPID.store (processInfo.dwProcessId);
1162 jStdout[0].Close ();
1163 jStderr[0].Close ();
1166 AutoHANDLE_& useSTDIN = jStdin[0];
1167 Assert (jStdin[1] == INVALID_HANDLE_VALUE);
1168 AutoHANDLE_& useSTDOUT = jStdout[1];
1169 Assert (jStdout[0] == INVALID_HANDLE_VALUE);
1170 AutoHANDLE_& useSTDERR = jStderr[1];
1171 Assert (jStderr[0] == INVALID_HANDLE_VALUE);
1173 constexpr size_t kStackBufReadAtATimeSize_ = 10 * 1024;
1176 if (p == INVALID_HANDLE_VALUE) {
1179 byte buf[kReadBufSize_];
1180#if qUsePeekNamedPipe_
1181 DWORD nBytesAvail{};
1187#
if qUsePeekNamedPipe_
1188 ::PeekNamedPipe (p,
nullptr,
nullptr,
nullptr, &nBytesAvail,
nullptr) and nBytesAvail != 0 and
1190 ::ReadFile (p, buf,
sizeof (buf), &nBytesRead,
nullptr) and nBytesRead > 0) {
1192 o.Write (span{buf, nBytesRead});
1194#if USE_NOISY_TRACE_IN_THIS_MODULE_
1195 buf[(nBytesRead == std::size (buf)) ? (std::size (buf) - 1) : nBytesRead] = byte{
'\0'};
1196 DbgTrace (
"read from process (fd={}) nBytesRead = {}: {}"_f, p, nBytesRead, buf);
1201 if (options.fDetached) {
1202 Assert (useSTDIN == INVALID_HANDLE_VALUE and useSTDOUT == INVALID_HANDLE_VALUE and useSTDERR == INVALID_HANDLE_VALUE);
1203 SAFE_HANDLE_CLOSER_ (&processInfo.hProcess);
1204 SAFE_HANDLE_CLOSER_ (&processInfo.hThread);
1208 Assert (processInfo.hProcess != INVALID_HANDLE_VALUE);
1209 if (processInfo.hProcess != INVALID_HANDLE_VALUE) {
1215 auto mkPipeNoWait_ = [] (HANDLE ioHandle) ->
void {
1216 if (ioHandle != INVALID_HANDLE_VALUE) {
1218 Verify (::GetNamedPipeHandleState (ioHandle, &mode,
nullptr,
nullptr,
nullptr,
nullptr, 0));
1219 mode |= PIPE_NOWAIT;
1220 Verify (::SetNamedPipeHandleState (ioHandle, &mode,
nullptr,
nullptr));
1223 mkPipeNoWait_ (useSTDIN);
1224 mkPipeNoWait_ (useSTDOUT);
1225 mkPipeNoWait_ (useSTDERR);
1231 if (in !=
nullptr) {
1232 byte stdinBuf[kStackBufReadAtATimeSize_];
1234 while (
size_t nbytes = in.
ReadBlocking (span{stdinBuf}).size ()) {
1235 Assert (nbytes <= std::size (stdinBuf));
1236 const byte* p = begin (stdinBuf);
1237 const byte* e = p + nbytes;
1240 if (::WriteFile (useSTDIN, p, Math::PinToMaxForType<DWORD> (e - p), &written,
nullptr) == 0) {
1241 DWORD lastErr = ::GetLastError ();
1247 if (lastErr != ERROR_SUCCESS and lastErr != ERROR_NO_MORE_FILES and lastErr != ERROR_PIPE_BUSY and lastErr != ERROR_NO_DATA) {
1248 DbgTrace (
"in RunExternalProcess_ - throwing {} while fill in stdin"_f, lastErr);
1249 ThrowSystemErrNo (lastErr);
1252 Assert (written <=
static_cast<size_t> (e - p));
1256 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1257 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1259 if (p < e and written == 0) {
1266 if (Time::GetTickCount () > timeoutAt) {
1267 DbgTrace (_T (
"process timed out (writing initial data) - so throwing up!"));
1269 (void)::TerminateProcess (processInfo.hProcess, -1);
1270 Throw (Execution::Platform::Windows::Exception (ERROR_TIMEOUT));
1285 int timesWaited = 0;
1294 HANDLE events[1] = {processInfo.hProcess};
1301 double remainingTimeout = (timesWaited <= 5) ? 0.1 : 0.5;
1303 ::WaitForMultipleObjects (
static_cast<DWORD
> (std::size (events)), events,
false,
static_cast<int> (remainingTimeout * 1000));
1306 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1307 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1308 switch (waitResult) {
1309 case WAIT_OBJECT_0: {
1310#if USE_NOISY_TRACE_IN_THIS_MODULE_
1311 DbgTrace (
"external process finished (DONE)"_f);
1314 goto DoneWithProcess;
1316 case WAIT_TIMEOUT: {
1317 DbgTrace (
"still waiting for external process output (WAIT_TIMEOUT)"_f);
1323 DWORD processExitCode{};
1324 Verify (::GetExitCodeProcess (processInfo.hProcess, &processExitCode));
1326 SAFE_HANDLE_CLOSER_ (&processInfo.hProcess);
1327 SAFE_HANDLE_CLOSER_ (&processInfo.hThread);
1329 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1330 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1332 if (runneeDetails ==
nullptr) {
1333 if (processExitCode != 0) {
1338#if USE_NOISY_TRACE_IN_THIS_MODULE_
1339 DbgTrace (
"storing process status (ExitCode): {}"_f,
static_cast<int> (processExitCode));
1341 if (processExitCode != 0) {
1342 DbgTrace (
"storing process status (ExitCode): {}"_f,
static_cast<int> (processExitCode));
1351 if (processInfo.hProcess != INVALID_HANDLE_VALUE and processInfo.hProcess !=
nullptr) {
1352 (void)::TerminateProcess (processInfo.hProcess,
static_cast<UINT
> (-1));
1353 SAFE_HANDLE_CLOSER_ (&processInfo.hProcess);
1354 SAFE_HANDLE_CLOSER_ (&processInfo.hThread);
1361tuple<function<void ()>, shared_ptr<ProcessRunner::DetailedRunnableRep_>> ProcessRunner::CreateDetailedRunnable_ ()
1363#if USE_NOISY_TRACE_IN_THIS_MODULE_
1367 auto resultDetails = MakeSharedPtr<DetailedRunnableRep_> ();
1369 [resultDetails, exe = this->fExecutable_, cmdLine = this->fArgs_, options = fOptions_, in = fStdIn_, out = fStdOut_, err = fStdErr_] () {
1370#if USE_NOISY_TRACE_IN_THIS_MODULE_
1373 auto activity =
LazyEvalActivity{[&] () {
return "executing '{}'"_f(cmdLine); }};
1375#if qStroika_Foundation_Common_Platform_POSIX
1376 Process_Runner_POSIX_ (resultDetails, exe, cmdLine, options, in, out, err);
1377#elif qStroika_Foundation_Common_Platform_Windows
1378 Process_Runner_Windows_ (resultDetails, exe, cmdLine, options, in, out, err);
1384function<void ()> ProcessRunner::CreateSimpleRunnable_ ()
1387 Assert (not fOptions_.fDetached);
1389 return [exe = this->fExecutable_, cmdLine = this->fArgs_, options = fOptions_, in = fStdIn_, out = fStdOut_, err = fStdErr_] () {
1390#if USE_NOISY_TRACE_IN_THIS_MODULE_
1393 auto activity =
LazyEvalActivity{[&] () {
return "executing '{}'"_f(cmdLine); }};
1395#if qStroika_Foundation_Common_Platform_POSIX
1396 Process_Runner_POSIX_ (
nullptr, exe, cmdLine, options, in, out, err);
1397#elif qStroika_Foundation_Common_Platform_Windows
1398 Process_Runner_Windows_ (
nullptr, 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 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)
A Mapping uniquely associates two elements: a key and a value (use Assocation to allow multiple value...
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.
unique_lock< AssertExternallySynchronizedChecker > WriteContext
Instantiate AssertExternallySynchronizedChecker::WriteContext to designate an area of code where prot...
shared_lock< const AssertExternallySynchronizedChecker > ReadContext
Instantiate AssertExternallySynchronizedChecker::ReadContext to designate an area of code where prote...
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 String ToString() 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 an external command, with stdin/stdout/stderr as strings or as streams - like perl backticks.
nonvirtual void Run(const Streams::InputStream::Ptr< byte > &in, const Streams::OutputStream::Ptr< byte > &out=nullptr, const Streams::OutputStream::Ptr< byte > &error=nullptr, Time::DurationSeconds timeout=Time::kInfinity)
Run the command synchronously, returning its output, and THROW on any failure.
ProcessRunner()=delete
Construct ProcessRunner with a CommandLine to run (doesn't actually RUN til you call Run or RunInBack...
nonvirtual BackgroundProcess RunInBackground(const Streams::InputStream::Ptr< byte > &in=nullptr, const Streams::OutputStream::Ptr< byte > &out=nullptr, const Streams::OutputStream::Ptr< byte > &error=nullptr)
Run the given external command/process (set by constructor) - with the given arguments in the backgro...
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...
nonvirtual void ThrowIfDoneWithException() const
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)
nonvirtual String ToString() const