问题描述
这已经被问过,但我无法找到一个明确的答案,在code。
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?
感谢
code是AP preciated。
Code is appreciated.
推荐答案
检查this螺纹 的工作中分组的过程。
Check this thread for grouping processes within a "job".
如果不为你工作,一个土生土长的做法可能会去如下:
If that does not work for you, a home grown approach might go as follows:
- 让你的主进程ID
- 呼叫CreateToolhelp32Snapshot到enumerateall系统上的程序
- 检查PROCESSENTRY32结构的th32ParentProcessID成员上的每个进程,如果你的父母ID匹配,则终止该进程(使用TerminateProcess)
- 所有的孩子都结束后,终止主要工艺
样code:
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适用于Windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!