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

查看:459
本文介绍了如何有效地杀死一个进程在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()通常不容易得到保持。如果你得到的是一个进程名称,那么你需要在机器上重复运行的进程。使用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天全站免登陆