Created
September 9, 2016 07:54
-
-
Save chuckleplant/295bbdd744692ec08a2321dffebb2502 to your computer and use it in GitHub Desktop.
Execute windows command and get results as string | Capture Output of Spawned Process to string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Execute a command and get the results in a CString. (Only standard output) | |
// | |
CStringA ExecCmd( | |
const wchar_t* cmd // [in] command to execute | |
) | |
{ | |
CStringA strResult; | |
HANDLE hPipeRead, hPipeWrite; | |
SECURITY_ATTRIBUTES saAttr = { sizeof(SECURITY_ATTRIBUTES) }; | |
saAttr.bInheritHandle = TRUE; //Pipe handles are inherited by child process. | |
saAttr.lpSecurityDescriptor = NULL; | |
// Create a pipe to get results from child's stdout. | |
if ( !CreatePipe(&hPipeRead, &hPipeWrite, &saAttr, 0) ) | |
return strResult; | |
STARTUPINFO si = { sizeof(STARTUPINFO) }; | |
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; | |
si.hStdOutput = hPipeWrite; | |
si.hStdError = hPipeWrite; | |
si.wShowWindow = SW_HIDE; // Prevents cmd window from flashing. Requires STARTF_USESHOWWINDOW in dwFlags. | |
PROCESS_INFORMATION pi = { 0 }; | |
BOOL fSuccess = CreateProcessW( NULL, (LPWSTR)cmd, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi); | |
if (! fSuccess) | |
{ | |
CloseHandle( hPipeWrite ); | |
CloseHandle( hPipeRead ); | |
return strResult; | |
} | |
bool bProcessEnded = false; | |
for (; !bProcessEnded ;) | |
{ | |
// Give some timeslice (50ms), so we won't waste 100% cpu. | |
bProcessEnded = WaitForSingleObject( pi.hProcess, 50) == WAIT_OBJECT_0; | |
// Even if process exited - we continue reading, if there is some data available over pipe. | |
for (;;) | |
{ | |
char buf[1024]; | |
DWORD dwRead = 0; | |
DWORD dwAvail = 0; | |
if (!::PeekNamedPipe(hPipeRead, NULL, 0, NULL, &dwAvail, NULL)) | |
break; | |
if (!dwAvail) // no data available, return | |
break; | |
if (!::ReadFile(hPipeRead, buf, min(sizeof(buf) - 1, dwAvail), &dwRead, NULL) || !dwRead) | |
// error, the child process might ended | |
break; | |
buf[dwRead] = 0; | |
strResult += buf; | |
} | |
} //for | |
CloseHandle( hPipeWrite ); | |
CloseHandle( hPipeRead ); | |
CloseHandle( pi.hProcess ); | |
CloseHandle( pi.hThread ); | |
return strResult; | |
} //ExecCmd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credit: http://stackoverflow.com/a/35658917/2628257