如何按名称杀死进程?(Win32 API) [英] How to kill processes by name? (Win32 API)
本文介绍了如何按名称杀死进程?(Win32 API)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上,我有一个将多次启动的程序.因此,该程序将启动两个或多个进程.
Basically, I have a program which will be launched more than once. So, there will be two or more processes launched of the program.
我想使用 Win32 API 并使用特定名称杀死/终止所有进程.
I want to use the Win32 API and kill/terminate all the processes with a specific name.
我见过杀死A进程的例子,但没有看到多个具有完全相同名称(但参数不同)的进程.
I have seen examples of killing A process, but not multiple processes with the exact same name(but different parameters).
推荐答案
试试下面的代码,killProcessByName()
会杀死任何名为 filename
的进程:
Try below code, killProcessByName()
will kill any process with name filename
:
#include <windows.h>
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#include <string.h>
void killProcessByName(const char *filename)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof (pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes)
{
if (strcmp(pEntry.szExeFile, filename) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD) pEntry.th32ProcessID);
if (hProcess != NULL)
{
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
int main()
{
killProcessByName("notepad++.exe");
return 0;
}
注意:代码对filename
区分大小写,您可以编辑不区分大小写.
Note: The code is case sensitive to filename
, you can edit it for case insensitive.
这篇关于如何按名称杀死进程?(Win32 API)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文