I have a function that is supposed to launch a group of processes by passing a command to CreateProcess. I am calling this function two times serially, but somehow the function exits and gets called the second time before the processes from the first group are finished.
It seems to wait for only one of the processes to exit. The next batch is launched when I close one of the applications from the first group of processes.
I am using it to launch a group of applications together, and launch the next group when all of those processes exit. Why is my WaitForMultipleObjects call not waiting for all of the processes in the group to exit?
void ProcessLauncher::launch_processes(PROCESS_LIST_TYPE& processes)
{
unsigned long const CP_MAX_COMMANDLINE = 32768;
VECTOR_TYPE<PROCESS_INFORMATION> procs;
VECTOR_TYPE<HANDLE> pHandles;
for (auto proc : processes)
{
STRING_TYPE command = proc.program_name + L" " + proc.params;
STARTUPINFO sinfo = { 0 };
sinfo.cb = sizeof(STARTUPINFO);
PROCESS_INFORMATION pi = { 0 };
try {
CHAR_TYPE* commandline = new CHAR_TYPE[CP_MAX_COMMANDLINE];
wcsncpy_s(commandline, CP_MAX_COMMANDLINE, command.c_str(), command.size() + 1);
CreateProcess(nullptr,
commandline,
nullptr,
nullptr,
false,
0,
nullptr,
nullptr,
&sinfo,
&pi);
delete[]commandline;
CloseHandle(pi.hThread);
procs.push_back(pi);
pHandles.push_back(pi.hProcess);
}
catch (std::bad_alloc&) {
std::wcerr << L"Insufficient memory to launch application" << std::endl;
return;
}
}
if (WAIT_FAILED == WaitForMultipleObjects(pHandles.size(), pHandles.data(), TRUE, INFINITE))
std::wcout << L"Failure waiting for process to terminate" << std::endl;
}
As IInspectable lead me to find, the CreateProcess call was failing to create the process but I was still adding the handles to the vector. I changed it to only add the handles to the vector if CreateProcess returned an equivalent value to TRUE.