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, spawn 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 = { 0 }; PROCESS_INFORMATION pi = { 0 }; DWORD dwExitCode; si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; BOOL 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) { const 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.