Stroika Library 3.0d16
 
Loading...
Searching...
No Matches
Foundation/Execution/Process.cpp
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2025. All rights reserved
3 */
4#include "Stroika/Foundation/StroikaPreComp.h"
5
6#include "Finally.h"
7
8#include "Process.h"
9
10using namespace Stroika::Foundation;
11using namespace Stroika::Foundation::Common;
12using namespace Stroika::Foundation::Execution;
13
14// Comment this in to turn on aggressive noisy DbgTrace in this module
15//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
16
17/*
18 ********************************************************************************
19 ********************** Execution::IsProcessRunning *****************************
20 ********************************************************************************
21 */
22
24{
25#if USE_NOISY_TRACE_IN_THIS_MODULE_
26 Debug::TraceContextBumper traceCtx{"Stroika::Foundation::Execution::IsProcessRunning", "pid={}"_f, pid};
27#endif
28#if qStroika_Foundation_Common_Platform_POSIX
29 // http://stackoverflow.com/questions/9152979/check-if-process-exists-given-its-pid
30 // http://linux.die.net/man/2/getpgid
31 // if not owner, trick of kill (pid, 0) returns error EPERM
32 pid_t tmp{::getpgid (pid)};
33#if USE_NOISY_TRACE_IN_THIS_MODULE_
34 DbgTrace ("getpgid (pid={}) -> {}, with ernno={}"_f, pid, tmp, errno);
35#endif
36 return tmp > 0;
37#elif qStroika_Foundation_Common_Platform_Windows
38 HANDLE process = ::OpenProcess (SYNCHRONIZE, FALSE, pid);
39 if (process == nullptr) {
40 // This can fail for a variety of reasons, including permissions, and because the process died a long time ago.
41 // Probably best answer here is just to return no, that its not running
42 return false;
43 }
44 [[maybe_unused]] auto&& cleanup = Execution::Finally ([&] () noexcept { ::CloseHandle (process); });
45 constexpr bool kUseGetExitCodeProcess_{false}; // GetExitCodeProcess can get confused by bad error code so WFSO probably better
46 if constexpr (kUseGetExitCodeProcess_) {
47 DWORD exitCode{};
48 return ::GetExitCodeProcess (process, &exitCode) and exitCode == STILL_ACTIVE;
49 }
50 else {
51 return ::WaitForSingleObject (process, 0) == WAIT_TIMEOUT;
52 }
53#else
55 return false;
56#endif
57}
#define AssertNotImplemented()
Definition Assertions.h:401
#define DbgTrace
Definition Trace.h:309
auto Finally(FUNCTION &&f) -> Private_::FinallySentry< FUNCTION >
Definition Finally.inl:31
int pid_t
TODO - maybe move this to configuraiotn module???
Definition Module.h:34