I create a process A which creates a process B. I want to terminate the whole process tree if a certain condition is met, so I follow the instructions provided here: Terminate a process tree (C for Windows)
The sample code works fine, it kills the child and the main process, but I receive an error in ::Process32Next(hSnap, &pe) ERROR_NO_MORE_FILES.
To be more specific, when the pe.th32ParentProcessID == dwPid and child process is terminated, in the next iteration ::Process32Next(hSnap, &pe) returns false with error code 18 (ERROR_NO_MORE_FILES)
Is this correct or I am doing something wrong?
void MyClass::winKillProcess(DWORD dwPid) try {
PROCESSENTRY32 pe;
memset(&pe, 0, sizeof(PROCESSENTRY32));
pe.dwSize = sizeof(PROCESSENTRY32);
HANDLE hSnap = :: CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (::Process32First(hSnap, &pe))
{
BOOL bContinue = TRUE;
// kill child processes
while (bContinue)
{
// only kill child processes
if (pe.th32ParentProcessID == dwPid)
{
HANDLE hChildProc = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
if (hChildProc)
{
::TerminateProcess(hChildProc, 1);
::CloseHandle(hChildProc);
}
}
bContinue = ::Process32Next(hSnap, &pe);
}
// kill the main process
HANDLE hProc = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPid);
if (hProc)
{
::TerminateProcess(hProc, 1);
::CloseHandle(hProc);
}
}
} catch (...) {
error_notify("winKillProcess() threw an unknown exception");
return;
}