1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| std::string GetCmdResult(const std::string& cmd) { SECURITY_ATTRIBUTES sa; ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES)); sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; HANDLE hReadPipe, hWritePipe; if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0)) { OutputDebugString("管道创建失败!"); return ""; }
BOOL ret = FALSE; STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(STARTUPINFO)); ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); si.cb = sizeof(STARTUPINFO); si.dwFlags |= STARTF_USESTDHANDLES; si.hStdInput = NULL; si.hStdError = hWritePipe; si.hStdOutput = hWritePipe;
ret = CreateProcess(NULL, const_cast<char*>(cmd.c_str()), NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);
if (ret) { CloseHandle(hWritePipe);
std::string resStr; char pBuf[BUFFER_SIZE] = { 0 }; DWORD readSize = 0; while (ReadFile(hReadPipe, pBuf, BUFFER_SIZE, &readSize, NULL)) { resStr += pBuf; ZeroMemory(pBuf, BUFFER_SIZE); } CloseHandle(hReadPipe); CloseHandle(pi.hProcess); CloseHandle(pi.hThread);
return resStr; } else { CloseHandle(hWritePipe); CloseHandle(hReadPipe); return ""; } }
|