15#pragma comment(lib, "psapi.lib")
23std::wstring toWideString(
const std::string& str)
27 int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1,
nullptr, 0);
28 std::wstring result(len - 1, L
'\0');
29 MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, result.data(), len);
33std::string toNarrowString(
const std::wstring& wstr)
37 int len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1,
nullptr, 0,
nullptr,
nullptr);
38 std::string result(len - 1,
'\0');
39 WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, result.data(), len,
nullptr,
nullptr);
48 std::optional<uint64_t> launch(
const std::string& executable,
49 const std::vector<std::string>& args,
50 const std::string& workingDir,
51 const std::map<std::string, std::string>& env,
52 bool detached)
override
55 std::wstring cmdLine = L
"\"" + toWideString(executable) + L
"\"";
56 for (
const auto& arg : args)
58 cmdLine += L
" \"" + toWideString(arg) + L
"\"";
62 std::wstring envBlock;
65 for (
const auto& [key, value] : env)
67 envBlock += toWideString(key) + L
"=" + toWideString(value) + L
'\0';
72 STARTUPINFOW si = {
sizeof(si)};
73 PROCESS_INFORMATION pi = {};
75 DWORD flags = detached ? CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS : 0;
77 std::wstring wideWorkingDir = toWideString(workingDir);
80 CreateProcessW(
nullptr, cmdLine.data(),
nullptr,
nullptr, FALSE, flags,
81 env.empty() ?
nullptr : envBlock.data(),
82 workingDir.empty() ?
nullptr : wideWorkingDir.c_str(), &si, &pi);
86 uint64_t pid =
static_cast<uint64_t
>(pi.dwProcessId);
87 CloseHandle(pi.hThread);
88 CloseHandle(pi.hProcess);
95 std::optional<uint64_t> launchShell(
const std::string& command,
const std::string& workingDir,
96 bool detached)
override
98 return launch(
"cmd.exe", {
"/c", command}, workingDir, {}, detached);
101 bool isRunning(uint64_t pid)
const override
104 OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
static_cast<DWORD
>(pid));
108 bool running = GetExitCodeProcess(hProcess, &exitCode) && exitCode == STILL_ACTIVE;
109 CloseHandle(hProcess);
115 std::optional<ProcessInfo> getProcessInfo(uint64_t pid)
const override
117 HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, FALSE,
118 static_cast<DWORD
>(pid));
126 wchar_t exePath[MAX_PATH];
127 DWORD size = MAX_PATH;
128 if (QueryFullProcessImageNameW(hProcess, 0, exePath, &size))
130 info.executablePath = toNarrowString(exePath);
132 std::filesystem::path p(info.executablePath);
133 info.name = p.filename().string();
138 info.cmdLine = info.executablePath;
141 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
142 if (hSnapshot != INVALID_HANDLE_VALUE)
144 PROCESSENTRY32W pe = {
sizeof(pe)};
145 if (Process32FirstW(hSnapshot, &pe))
149 if (pe.th32ProcessID ==
static_cast<DWORD
>(pid))
151 info.parentPid = pe.th32ParentProcessID;
154 }
while (Process32NextW(hSnapshot, &pe));
156 CloseHandle(hSnapshot);
159 CloseHandle(hProcess);
163 std::vector<ProcessInfo> findByName(
const std::string& name)
const override
165 std::vector<ProcessInfo> results;
166 std::wstring wideName = toWideString(name);
168 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
169 if (hSnapshot == INVALID_HANDLE_VALUE)
172 PROCESSENTRY32W pe = {
sizeof(pe)};
173 if (Process32FirstW(hSnapshot, &pe))
177 if (_wcsicmp(pe.szExeFile, wideName.c_str()) == 0)
180 info.pid = pe.th32ProcessID;
181 info.name = toNarrowString(pe.szExeFile);
182 info.parentPid = pe.th32ParentProcessID;
183 results.push_back(info);
185 }
while (Process32NextW(hSnapshot, &pe));
188 CloseHandle(hSnapshot);
192 std::vector<ProcessInfo> findByCommandLine(
const std::string& pattern)
const override
196 std::vector<ProcessInfo> results;
198 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
199 if (hSnapshot == INVALID_HANDLE_VALUE)
202 PROCESSENTRY32W pe = {
sizeof(pe)};
203 if (Process32FirstW(hSnapshot, &pe))
207 std::string exeName = toNarrowString(pe.szExeFile);
208 if (exeName.find(pattern) != std::string::npos)
211 info.pid = pe.th32ProcessID;
213 info.parentPid = pe.th32ParentProcessID;
214 results.push_back(info);
216 }
while (Process32NextW(hSnapshot, &pe));
219 CloseHandle(hSnapshot);
223 std::vector<ProcessInfo> getChildren(uint64_t parentPid)
const override
225 std::vector<ProcessInfo> results;
227 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
228 if (hSnapshot == INVALID_HANDLE_VALUE)
231 PROCESSENTRY32W pe = {
sizeof(pe)};
232 if (Process32FirstW(hSnapshot, &pe))
236 if (pe.th32ParentProcessID ==
static_cast<DWORD
>(parentPid))
239 info.pid = pe.th32ProcessID;
240 info.name = toNarrowString(pe.szExeFile);
241 info.parentPid = pe.th32ParentProcessID;
242 results.push_back(info);
244 }
while (Process32NextW(hSnapshot, &pe));
247 CloseHandle(hSnapshot);
251 std::vector<ProcessInfo> getAllProcesses()
const override
253 std::vector<ProcessInfo> results;
255 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
256 if (hSnapshot == INVALID_HANDLE_VALUE)
259 PROCESSENTRY32W pe = {
sizeof(pe)};
260 if (Process32FirstW(hSnapshot, &pe))
265 info.pid = pe.th32ProcessID;
266 info.name = toNarrowString(pe.szExeFile);
267 info.parentPid = pe.th32ParentProcessID;
268 results.push_back(info);
269 }
while (Process32NextW(hSnapshot, &pe));
272 CloseHandle(hSnapshot);
276 bool terminate(uint64_t pid,
bool force)
override
278 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE,
static_cast<DWORD
>(pid));
281 BOOL result = TerminateProcess(hProcess, 1);
282 CloseHandle(hProcess);
288 bool terminateTree(uint64_t pid)
override
291 auto children = getChildren(pid);
292 for (
const auto& child : children)
294 terminateTree(child.pid);
296 return terminate(pid,
true);
299 int waitForExit(uint64_t pid, uint32_t timeoutMs)
override
301 HANDLE hProcess = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
302 static_cast<DWORD
>(pid));
306 DWORD waitResult = WaitForSingleObject(hProcess, timeoutMs == 0 ? INFINITE : timeoutMs);
308 if (waitResult == WAIT_OBJECT_0)
311 if (GetExitCodeProcess(hProcess, &exitCode))
313 CloseHandle(hProcess);
314 return static_cast<int>(exitCode);
318 CloseHandle(hProcess);
322 std::pair<int, std::string> executeAndCapture(
const std::string& command,
323 uint32_t timeoutMs)
override
325 SECURITY_ATTRIBUTES sa = {
sizeof(sa),
nullptr, TRUE};
326 HANDLE hReadPipe, hWritePipe;
328 if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0))
333 SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);
335 STARTUPINFOW si = {
sizeof(si)};
336 si.dwFlags = STARTF_USESTDHANDLES;
337 si.hStdOutput = hWritePipe;
338 si.hStdError = hWritePipe;
339 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
341 PROCESS_INFORMATION pi = {};
343 std::wstring cmdLine = L
"cmd.exe /c " + toWideString(command);
345 BOOL success = CreateProcessW(
nullptr, cmdLine.data(),
nullptr,
nullptr, TRUE,
346 CREATE_NO_WINDOW,
nullptr,
nullptr, &si, &pi);
348 CloseHandle(hWritePipe);
352 CloseHandle(hReadPipe);
357 std::array<char, 4096> buffer;
360 while (ReadFile(hReadPipe, buffer.data(),
static_cast<DWORD
>(buffer.size()), &bytesRead,
364 output.append(buffer.data(), bytesRead);
367 CloseHandle(hReadPipe);
369 WaitForSingleObject(pi.hProcess, timeoutMs == 0 ? INFINITE : timeoutMs);
372 GetExitCodeProcess(pi.hProcess, &exitCode);
374 CloseHandle(pi.hThread);
375 CloseHandle(pi.hProcess);
377 return {
static_cast<int>(exitCode), output};
384 return std::make_unique<WindowsProcessManager>();