I intent to encapsulate a function to execute a command with C++. code as below:
std::string ExecuteCommand(const std::string& command)
{
SECURITY_ATTRIBUTES saAttr;
HANDLE hReadPipe, hWritePipe;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&hReadPipe, &hWritePipe, &saAttr, 0)) {
return "";
}
if (!SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0)) {
return "";
}
DWORD dwMode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
if (!SetNamedPipeHandleState(hReadPipe, &dwMode, NULL, NULL)) {
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
return "";
}
STARTUPINFOA si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.hStdError = hWritePipe;
si.hStdOutput = hWritePipe;
si.dwFlags |= STARTF_USESTDHANDLES;
if (!CreateProcessA(NULL, (LPSTR)command.c_str(), NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
std::cout << ::GetLastError() << std::endl;
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
return "";
}
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD dwBytesRead;
CHAR chBuffer[4096];
std::string output;
while (ReadFile(hReadPipe, chBuffer, sizeof(chBuffer) - 1, &dwBytesRead, NULL) != FALSE) {
if (dwBytesRead == 0) {
break;
}
chBuffer[dwBytesRead] = '\0';
output += chBuffer;
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
return output;
}
and then, i try write some unit test for this function.
- std::cout << ExecuteCommand("ipconfig /all") << std::endl;
- std::cout << ExecuteCommand("netsh mbn show interface");
- std::cout << ExecuteCommand("logman") << std::endl;
- std::cout << ExecuteCommand("logman /?") << std::endl; case 1: OK case 2: The following command was not found: mbn show interface. case 3: freezeļ¼blocking in function WaitForSingleObject(pi.hProcess, INFINITE); case 4: freeze, blocking in function WaitForSingleObject(pi.hProcess, INFINITE);
i've tried quoting the parameters, passing an absulute path, noting helps. Test environment: Windows 10, Visual Studio 2019, console appliation
help function for execute commands