本文介绍了终止进程树(C for Windows)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前有人问过这个问题,但我在代码中找不到明确的答案.

This has been asked before but I can't find a definitive answer, in code.

我打开了一个进程 ProcessA(PID 为 1234).此进程打开一个子进程 ProcessAB (PID 5678).完成后我终止了 ProcessA 但我仍然有 ProcessAB 挥之不去.

I open a process, ProcessA (with PID 1234). This process opens a child process, ProcessAB (PID 5678).After I'm done I terminate ProcessA but I still have the lingering of ProcessAB.

如何终止整个进程树?我的意思是,我如何确保如果我终止了我打开的进程,我也会终止所有关联的进程?

How do I terminate the whole process tree? What I mean, how do I make sure that if I terminate the process I opened I am also terminating all the associated processes?

谢谢

感谢代码.

推荐答案

检查 此线程 用于在作业"中对进程进行分组.

Check this thread for grouping processes within a "job".

如果这对您不起作用,可以采用以下自家培育的方法:

If that does not work for you, a home grown approach might go as follows:

  1. 获取您的主进程 ID
  2. 调用 CreateToolhelp32Snapshot 枚举系统上的所有进程
  3. 检查每个进程的 PROCESSENTRY32 结构的 th32ParentProcessID 成员,如果它与您的父 ID 匹配,则终止进程(使用 终止进程)
  4. 在所有子进程终止后,终止主进程

示例代码:

    DWORD myprocID = 1234; // your main process id

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 == myprocID)
        {
            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, myprocID);

    if (hProc)
    {
        ::TerminateProcess(hProc, 1);
        ::CloseHandle(hProc);
    }
}

这篇关于终止进程树(C for Windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 16:03