Browse - Programming Tips - How can I run a command with no window (DOS box) and wait for the result?
Date: 2016apr4
OS: Windows
Language: C/C++
Keywords: command prompt
Q. How can I run a command with no window (DOS box) and wait for the result?
A. Use this:
BOOL ExecCommandAndWait(LPCSTR szCmdLine)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
BOOL bResult;
DWORD dwExitCode;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
bResult = CreateProcess(
NULL, // pointer to name of executable module - NULL means find the first space-delimited word.
(LPSTR)szCmdLine, // pointer to command line string
NULL, // pointer to process security attributes
NULL, // pointer to thread security attributes
FALSE, // Don't inherit handles
NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, // Creation flags
NULL, // pointer to new environment block
NULL, // pointer to current directory name
&si, // pointer to STARTUPINFO
&pi // pointer to PROCESS_INFORMATION
);
if (!bResult)
{
DWORD dwError = GetLastError();
printf("Could not run: %s\n", szCmdLine);
printf("Error: %d\n", dwError);
return bResult;
}
WaitForSingleObject(pi.hProcess, INFINITE);
bResult = GetExitCodeProcess(pi.hProcess, &dwExitCode);
CloseHandle(pi.hProcess); // Cleanup
CloseHandle(pi.hThread); // Cleanup
return bResult;
}
You can not use system() since it will show a DOS box.
You can not use WinExec() since it doesn't wait.