My goal is to run a command line batch script (from a .bat
file) without displaying the console window, and wait for it to finish running before continuing. I'm using the example from here. So I came up with the following code:
//NOTE: Error checks are omitted for brevity
//Get path to cmd.exe
WCHAR buffCmd[1024];
::GetEnvironmentVariable(L"ComSpec", buffCmd, 1024);
std::wstring runPath = buffCmd;
runPath = runPath + L" /C \"path-to\\test.bat\"";
LPWCH pEnvStrs = ::GetEnvironmentStrings();
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(si);
::CreateProcess(NULL, &runPath[0], NULL, NULL, FALSE,
/*CREATE_NO_WINDOW | */ //Will uncomment it when I make it work
CREATE_UNICODE_ENVIRONMENT,
pEnvStrs, NULL, &si, &pi);
HANDLE hProc = pi.hProcess;
::WaitForSingleObject(hProc, INFINITE);
DWORD dwProcExitCode = 0xCCCCCCCC;
::GetExitCodeProcess(hProc, &dwProcExitCode);
//Clean up
::FreeEnvironmentStrings(pEnvStrs);
::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
And the batch test.bat
file is just this:
notepad
But when I run it, and use /K
option instead of /C
to keep the console open, I get the following error in the console window that CreateProcess
opens up:
The filename, directory name, or volume label syntax is incorrect.
and cmd.exe
returns error code 1
.
So what am I missing here?
EDIT: Sorry, forgot to mention, I'm calling it from a GUI process.