如何有效地杀死 C++ (Win32) 中的进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1916574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to effectively kill a process in C++ (Win32)?
提问by Kristina Brooks
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.
我目前正在编写一个非常轻量级的程序,所以我必须使用 C++,因为它没有绑定到 .NET 框架,这会大大增加程序的大小。
I need to be able to terminate process and to do that I need to get a process handle. Unfortuanately I haven't figured how to do that yet.
我需要能够终止进程,为此我需要获得进程句柄。不幸的是,我还没有想出如何做到这一点。
P.S. I know that to kill a process you have to use TerminateProcess.
PS 我知道要杀死一个进程,你必须使用TerminateProcess。
采纳答案by Hans Passant
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.
OpenProcess() 所需的 PID 通常不容易掌握。如果你得到的只是一个进程名称,那么你需要迭代机器上正在运行的进程。使用 CreateToolhelp32Snapshot 执行此操作,然后使用 Process32First 并使用 Process32Next 循环。PROCESSENTRY32.szExeFile 为您提供进程名称(不是路径!),th32ProcessID 为您提供 PID。
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.
下一个考虑是该过程可能出现不止一次。并且有可能将相同的进程名称用于非常不同的程序。比如“设置”。如果您不只是想将它们全部杀死,则需要尝试从它们获取一些运行时信息。窗口标题栏文本,也许。GetProcessImageFileName() 可以为您提供 .exe 的路径。它使用本机内核格式,您需要 QueryDosDevice 将磁盘驱动器设备名称映射到驱动器号。
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.
下一个考虑是您在 OpenProcess() 中要求的权限。你不太可能得到PROCESS_ALL_ACCESS
,你需要的只是PROCESS_TERMINATE
。虽然这也是特权。确保您用于运行程序的帐户可以获得该权限。
回答by James Hugard
Rather than going through all that pain to kill a process with a known name, why not simply call out to "system" and ask the command-line to kill it?
与其经历所有痛苦来杀死一个已知名称的进程,为什么不简单地调用“系统”并要求命令行杀死它呢?
For example,
例如,
int retval = ::_tsystem( _T("taskkill /F /T /IM MyProcess.exe") );
回答by Kristina Brooks
HANDLE explorer;
explorer = OpenProcess(PROCESS_ALL_ACCESS,false,2120);
TerminateProcess(explorer,1);
That worked
那行得通
回答by Jon Benedicto
To get a handle to pass to TerminateProcess, use OpenProcessin combination with some other function like EnumProcesses.
为了获得一个句柄传递给了TerminateProcess,使用OpenProcess结合像其他一些功能EnumProcesses。
回答by Developer
Here is the full example for Visual Studio 2010 C++ project how to kill the process by the EXEfile name.
这是 Visual Studio 2010 C++ 项目如何通过EXE文件名终止进程的完整示例。
In order to check it just run Internet Explorer and after this execute following code.
为了检查它,只需运行 Internet Explorer,然后执行以下代码。
#include <iostream>
#include <string>
#include<tchar.h>
#include <process.h>
#include <windows.h>
#include <tlhelp32.h>
using namespace std;
// Forward declarations:
BOOL GetProcessList();
BOOL TerminateMyProcess(DWORD dwProcessId, UINT uExitCode);
int main( void )
{
GetProcessList( );
return 0;
}
BOOL GetProcessList( )
{
HANDLE hProcessSnap;
HANDLE hProcess;
PROCESSENTRY32 pe32;
DWORD dwPriorityClass;
// Take a snapshot of all processes in the system.
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
{
return( FALSE );
}
// Set the size of the structure before using it.
pe32.dwSize = sizeof( PROCESSENTRY32 );
// Retrieve information about the first process,
// and exit if unsuccessful
if( !Process32First( hProcessSnap, &pe32 ) )
{
CloseHandle( hProcessSnap ); // clean the snapshot object
return( FALSE );
}
// Now walk the snapshot of processes
do
{
string str(pe32.szExeFile);
if(str == "iexplore.exe") // put the name of your process you want to kill
{
TerminateMyProcess(pe32.th32ProcessID, 1);
}
} while( Process32Next( hProcessSnap, &pe32 ) );
CloseHandle( hProcessSnap );
return( TRUE );
}
BOOL TerminateMyProcess(DWORD dwProcessId, UINT uExitCode)
{
DWORD dwDesiredAccess = PROCESS_TERMINATE;
BOOL bInheritHandle = FALSE;
HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
if (hProcess == NULL)
return FALSE;
BOOL result = TerminateProcess(hProcess, uExitCode);
CloseHandle(hProcess);
return result;
}
Imagine in C# it looks like
想象一下在 C# 中它看起来像
using System;
using System.Collections.Generic;
using System.Text;
namespace MyProcessKiller
{
class Program
{
static void Main(string[] args)
{
foreach (System.Diagnostics.Process myProc in System.Diagnostics.Process.GetProcesses())
{
if (myProc.ProcessName == "iexplore")
{
myProc.Kill();
}
}
}
}
}
回答by user3290207
windows only
仅窗户
system("taskkill /f /im servicetokill.exe")
回答by laishiekai
Here are some working sample codes to kill a process called "ShouldBeDead.exe":
以下是一些用于终止名为“ShouldBeDead.exe”的进程的工作示例代码:
// you will need these headers, and you also need to link to Psapi.lib
#include <tchar.h>
#include <psapi.h>
...
// first get all the process so that we can get the process id
DWORD processes[1024], count;
if( !EnumProcesses( processes, sizeof(processes), &count ) )
{
return false;
}
count /= sizeof(DWORD);
for(unsigned int i = 0; i < count; i++)
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
if(processes[i] != 0)
{
// remember to open with PROCESS_ALL_ACCESS, otherwise you will not be able to kill it
HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, processes[i] );
if(NULL != hProcess)
{
HMODULE hMod;
DWORD cbNeeded;
if(EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
{
GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR));
// find the process and kill it
if(strcmp(szProcessName, "ShouldBeDead.exe") == 0)
{
DWORD result = WAIT_OBJECT_0;
while(result == WAIT_OBJECT_0)
{
// use WaitForSingleObject to make sure it's dead
result = WaitForSingleObject(hProcess, 100);
TerminateProcess(hProcess, 0);
}
CloseHandle(hProcess);
}
}
}
}
}
回答by Jason Orendorff
CreateProcess
and OpenProcess
return process handles.
CreateProcess
并OpenProcess
返回进程句柄。
Here's some sample codeto find a process by asking the system to list all processes and then searching the list for the process you want.
下面是一些示例代码,通过要求系统列出所有进程然后在列表中搜索您想要的进程来查找进程。