我们有一个c ++任务,它将分叉一个新进程.反过来,这个过程可能有几个子进程.如果任务超过规定的时间,我们将要杀死该分叉进程.但是,我们不希望孤立它产生的进程.我们希望他们都死了.我使用了Process Explorer,它有一个"杀死进程树"选项,类似于Windows任务管理器的"结束进程树",所以我猜/假设有一个公共API来执行此操作.有没有人这样做,或者知道对公共API的引用呢?
Thx,Brett
您可能想要考虑"Jobs API".CreateJobObject和朋友.您可以通过设置适当的属性来强制子进程保留在作业中.然后你可以随时调用TerminateJobObject.
澄清:这不是任务管理器所做的.
我建议去工作对象路线,如上所述,它将是最可靠的.如果您不能转到作业对象路由,则可以使用toolhelp API获取父进程ID并以此方式构建树.但是要小心,因为Windows没有强大的父/子关系,并且PID可以被回收.您可以使用GetProcessTimes查询进程的创建时间,并检查它是否比子进程旧.如果树中的中间进程终止,您将无法进一步遍历树.
// Error handling removed for brevity HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 process; ZeroMemory(&process, sizeof(process)); process.dwSize = sizeof(process); Process32First(snapshot, &process); do { // process.th32ProcessId is the PID. // process.th32ParentProcessID is the parent PID. } while (Process32Next(snapshot, &process));
有一个名为TerminateProcess()的Win32函数.它应该为你做的工作.
或者,我发现taskkill命令对这样的事情很有用.
从命令行:
taskkill /F /T /IM program.exe
来自代码:
system("taskkill /F /T /IM program.exe");
其他开关(直接来自taskkill /?):
TASKKILL [/S system [/U username [/P [password]]]] { [/FI filter] [/PID processid | /IM imagename] } [/F] [/T] Description: This command line tool can be used to end one or more processes. Processes can be killed by the process id or image name. Parameter List: /S system Specifies the remote system to connect to. /U [domain\]user Specifies the user context under which the command should execute. /P [password] Specifies the password for the given user context. Prompts for input if omitted. /F Specifies to forcefully terminate process(es). /FI filter Displays a set of tasks that match a given criteria specified by the filter. /PID process id Specifies the PID of the process that has to be terminated. /IM image name Specifies the image name of the process that has to be terminated. Wildcard '*' can be used to specify all image names. /T Tree kill: terminates the specified process and any child processes which were started by it. /? Displays this help/usage.
-约翰