如何有效地杀死 C++ (Win32) 中的进程? [英] How to effectively kill a process in C++ (Win32)?

查看:26
本文介绍了如何有效地杀死 C++ (Win32) 中的进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个非常轻量级的程序,所以我必须使用 C++,因为它没有绑定到 .NET 框架,这会大大增加程序的大小.

I am currently writing a very lightweight program so I have to use C++ since it is not bound to .NET framework which drastically increases size of the program.

我需要能够终止进程,为此我需要获得进程句柄.不幸的是,我还没有想出如何做到这一点.

附言我知道要终止进程,您必须使用 TerminateProcess.

P.S. I know that to kill a process you have to use TerminateProcess.

推荐答案

OpenProcess() 所需的 PID 通常不容易掌握.如果你得到的只是一个进程名称,那么你需要迭代机器上正在运行的进程.使用 CreateToolhelp32Snapshot 执行此操作,然后使用 Process32First 并使用 Process32Next 循环.PROCESSENTRY32.szExeFile 为您提供进程名称(不是路径!),th32ProcessID 为您提供 PID.

The PID you need for OpenProcess() is not normally easy to get a hold of. If all you got is a process name then you need to iterate the running processes on the machine. Do so with CreateToolhelp32Snapshot, followed by Process32First and loop with Process32Next. The PROCESSENTRY32.szExeFile gives you the process name (not path!), th32ProcessID gives you the PID.

接下来的考虑是该过程可能会出现不止一次.并且有可能将相同的进程名称用于非常不同的程序.比如设置".如果您不只是想将它们全部杀死,则需要尝试从它们获取一些运行时信息.窗口标题栏文本,也许.GetProcessImageFileName() 可以为您提供 .exe 的路径.它使用本机内核格式,您需要 QueryDosDevice 将磁盘驱动器设备名称映射到驱动器号.

The next consideration is that the process may appear more than once. And there's a chance that the same process name is used for very different programs. Like "Setup". If you don't just want to kill them all, you'll need to try to obtain some runtime info from them. Window caption bar text, perhaps. GetProcessImageFileName() can give you the path to the .exe. It uses the native kernel format, you'd need QueryDosDevice to map a disk drive device name to a drive letter.

接下来要考虑的是您在 OpenProcess() 中要求的权限.您不太可能获得PROCESS_ALL_ACCESS,您只需要PROCESS_TERMINATE.虽然这也是特权.确保您用于运行程序的帐户可以获得该权限.

The next consideration is the rights you ask for in OpenProcess(). You are unlikely to get PROCESS_ALL_ACCESS, all you need is PROCESS_TERMINATE. Although that's privileged as well. Ensure the account you use to run your program can obtain that right.

这篇关于如何有效地杀死 C++ (Win32) 中的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆