0
votes

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;
}
1
How many processes are in the list in each invocation of your function?conio
@conio At the moment there are only two on each call.user3096803
@conio I forgot to mention some details about the wait. I added them in a blockquote to the question. The second batch is launched when I end one of the processes in the first group.user3096803
You aren't checking the process handles of your CreateProcess calls, and since you aren't properly quoting the application pathname for the command line, failure to create a process isn't just a theoretical possibility.IInspectable

1 Answers

0
votes

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.