From 5931c42cc6014927bce0843f67cc93f80931c227 Mon Sep 17 00:00:00 2001 From: momo5502 Date: Mon, 30 Jan 2017 17:47:29 +0100 Subject: [PATCH] [Runner] Workaround if we can't open the parent process --- src/STDInclude.hpp | 1 + src/Worker/Runner.cpp | 48 +++++++++++++++++++++++++++++++++---------- src/Worker/Runner.hpp | 1 + 3 files changed, 39 insertions(+), 11 deletions(-) diff --git a/src/STDInclude.hpp b/src/STDInclude.hpp index 4764310e..4400fcbf 100644 --- a/src/STDInclude.hpp +++ b/src/STDInclude.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #pragma warning(push) #pragma warning(disable: 4996) diff --git a/src/Worker/Runner.cpp b/src/Worker/Runner.cpp index afd27a15..ea213dbe 100644 --- a/src/Worker/Runner.cpp +++ b/src/Worker/Runner.cpp @@ -18,25 +18,35 @@ namespace Worker { printf("Attaching to parent process %d...\n", this->processId); HANDLE processHandle = OpenProcess(SYNCHRONIZE, FALSE, this->processId); - if (!processHandle || processHandle == INVALID_HANDLE_VALUE) + + if (!processHandle || processHandle == INVALID_HANDLE_VALUE && !Runner::isProcessAlive()) { printf("Unable to attach to parent process\n"); + return; + } + + printf("Successfully attached to parent process\n"); + printf("Starting worker...\n"); + + std::thread workerThread(&Runner::worker, this); + + if (!processHandle || processHandle == INVALID_HANDLE_VALUE) + { + while(this->isProcessAlive()) + { + std::this_thread::sleep_for(100ms); + } } else { - printf("Successfully attached to parent process\n"); - printf("Starting worker...\n"); - - std::thread workerThread(&Runner::worker, this); - WaitForSingleObject(processHandle, INFINITE); CloseHandle(processHandle); - - printf("Awaiting worker termination...\n"); - this->terminate = true; - if (workerThread.joinable()) workerThread.join(); - printf("Worker terminated\n"); } + + printf("Awaiting worker termination...\n"); + this->terminate = true; + if (workerThread.joinable()) workerThread.join(); + printf("Worker terminated\n"); } void Runner::attachHandler(Runner::Handler* handler) @@ -44,6 +54,22 @@ namespace Worker this->handlers[handler->getCommand()] = std::shared_ptr(handler); } + bool Runner::isProcessAlive() + { + DWORD aProcesses[1024], cbNeeded; + if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded)) return false; + + for(DWORD i = 0; i < cbNeeded / sizeof(DWORD); ++i) + { + if(aProcesses[i] == static_cast(this->processId)) + { + return true; + } + } + + return false; + } + void Runner::worker() { printf("Worker started\n"); diff --git a/src/Worker/Runner.hpp b/src/Worker/Runner.hpp index 31ad6731..9aa2784b 100644 --- a/src/Worker/Runner.hpp +++ b/src/Worker/Runner.hpp @@ -47,6 +47,7 @@ namespace Worker private: void worker(); + bool isProcessAlive(); int processId; bool terminate;