下面是具体代码
总共分为两个过程
enumproctree 主要用来枚举句柄树
killproc 关闭某个程序的进程
procedure enumproctree(const pid: dword;
out pid_tree: tpidtree);
procedure listtree(rootpid: dword);
var
hp_root: thandle;
found: boolean;
pn: tprocessentry32;
hsnap: thandle;
begin
hp_root := openprocess(process_all_access, false, rootpid);
if hp_root 0 then
begin
closehandle(hp_root);
setlength(pid_tree, length(pid_tree) + 1);
pid_tree[length(pid_tree) - 1] := rootpid;
hsnap := createtoolhelp32snapshot(th32cs_snapprocess, 0);
pn.dwsize := sizeof(tprocessentry32);
found := process32first(hsnap, pn);
while found do
begin
if rootpid = pn.th32parentprocessid then
begin
listtree(pn.th32processid);
end;
found := process32next(hsnap, pn);
end;
closehandle(hsnap);
end;
end;
begin
setlength(pid_tree, 0);
listtree(pid);
end;
killproc过程的参数:
pid需要结束的句柄id
killchild是否结束子进程
如果killchild是true,那么首先枚举所有的子句柄,然后一次性都关闭
procedure killproc(pid: dword; killchild: boolean = true; const exitcode: cardinal = 0);
var
i: integer;
hproc: thandle;
pid_tree: tpidtree;
begin
if killchild then
begin
enumproctree(pid, pid_tree);
for i := high(pid_tree) downto low(pid_tree) do
begin
if (pid_tree[i] 0) then
begin
hproc := openprocess(process_all_access, false, pid_tree[i]);
if hproc 0 then
begin
terminateprocess(hproc, exitcode);
closehandle(hproc);
end;
end;
end;
end
else
begin
hproc := openprocess(process_all_access, false, pid);
if hproc 0 then
begin
terminateprocess(hproc, exitcode);
closehandle(hproc);
end;
end;
end;
使用代码
killproc(lpprocessinformation.dwprocessid, true, result);
lpprocessinformation.dwprocessid 进程的句柄id
true结束子进程
本文地址:http://www.xszlo.com/article/2012-12-24/7746.html,转发请保留这个地址,谢谢
