|
| 1 | +/** |
| 2 | + * \file libipc/platform/win/process_impl.h |
| 3 | + * \author mutouyun ([email protected]) |
| 4 | + */ |
| 5 | +#pragma once |
| 6 | + |
| 7 | +#include <phnt_windows.h> |
| 8 | +#include <phnt.h> |
| 9 | + |
| 10 | +#include "libimp/log.h" |
| 11 | +#include "libipc/process.h" |
| 12 | + |
| 13 | +LIBIPC_NAMESPACE_BEG_ |
| 14 | +using namespace ::LIBIMP; |
| 15 | + |
| 16 | +/// \brief Experimental fork() on Windows. |
| 17 | +/// \see https://gist.github.com/Cr4sh/126d844c28a7fbfd25c6 |
| 18 | +/// https://github.com/huntandhackett/process-cloning |
| 19 | +namespace { |
| 20 | + |
| 21 | +typedef SSIZE_T pid_t; |
| 22 | + |
| 23 | +pid_t fork() { |
| 24 | + LIBIMP_LOG_(); |
| 25 | + |
| 26 | + RTL_USER_PROCESS_INFORMATION process_info; |
| 27 | + NTSTATUS status; |
| 28 | + |
| 29 | + /* lets do this */ |
| 30 | + status = RtlCloneUserProcess(RTL_CLONE_PROCESS_FLAGS_INHERIT_HANDLES |
| 31 | + , NULL, NULL, NULL, &process_info); |
| 32 | + if (status == STATUS_PROCESS_CLONED) { |
| 33 | + // Executing inside the clone... |
| 34 | + // Re-attach to the parent's console to be able to write to it |
| 35 | + FreeConsole(); |
| 36 | + AttachConsole(ATTACH_PARENT_PROCESS); |
| 37 | + return 0; |
| 38 | + } else { |
| 39 | + // Executing inside the original (parent) process... |
| 40 | + if (!NT_SUCCESS(status)) { |
| 41 | + log.error("failed: RtlCloneUserProcess(...)"); |
| 42 | + return -1; |
| 43 | + } |
| 44 | + return (pid_t)process_info.ProcessHandle; |
| 45 | + } |
| 46 | + |
| 47 | + /* NOTREACHED */ |
| 48 | +} |
| 49 | + |
| 50 | +#define WNOHANG 1 /* Don't block waiting. */ |
| 51 | + |
| 52 | +/// \see https://man7.org/linux/man-pages/man3/wait.3p.html |
| 53 | +/// https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntwaitforsingleobject |
| 54 | +pid_t waitpid(pid_t pid, int */*status*/, int options) { |
| 55 | + LIBIMP_LOG_(); |
| 56 | + if (pid == -1) { |
| 57 | + return -1; |
| 58 | + } |
| 59 | + if (options & WNOHANG) { |
| 60 | + return pid; |
| 61 | + } |
| 62 | + NTSTATUS status = NtWaitForSingleObject((HANDLE)pid, FALSE, NULL); |
| 63 | + if (!NT_SUCCESS(status)) { |
| 64 | + log.error("failed: NtWaitForSingleObject(...)"); |
| 65 | + return -1; |
| 66 | + } |
| 67 | + return pid; |
| 68 | +} |
| 69 | + |
| 70 | +} // namespace |
| 71 | +LIBIPC_NAMESPACE_END_ |
0 commit comments