問題描述
我目前正在編寫一個非常輕量級的程序,所以我必須使用 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) 中的進程?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!