基本上,我有一个不止一次推出的程序。因此,该计划将启动两个或更多流程。
我想使用Win32 API并使用特定名称终止/终止所有进程。
我已经看到了杀死进程的示例,但没有看到具有完全相同名称(但参数不同)的多个进程。
答案 0 :(得分:44)
尝试以下代码,killProcessByName()
会终止名为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
,您可以编辑它以区分大小写。
答案 1 :(得分:1)
我遇到了类似的问题。这就是我想出的......
void myClass::killProcess()
{
const int maxProcIds = 1024;
DWORD procList[maxProcIds];
DWORD procCount;
char* exeName = "ExeName.exe";
char processName[MAX_PATH];
// get the process by name
if (!EnumProcesses(procList, sizeof(procList), &procCount))
return;
// convert from bytes to processes
procCount = procCount / sizeof(DWORD);
// loop through all processes
for (DWORD procIdx=0; procIdx<procCount; procIdx++)
{
// get a handle to the process
HANDLE procHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procList[procIdx]);
// get the process name
GetProcessImageFileName(procHandle, processName, sizeof(processName));
// terminate all pocesses that contain the name
if (strstr(processName, exeName))
TerminateProcess(procHandle, 0);
CloseHandle(procHandle);
}
}
答案 2 :(得分:0)
void kill(std::string filename, int delay)
{
filename += ".exe";
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes) {
if (filename.c_str() == pEntry.szExeFile) {
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0, (DWORD)pEntry.th32ProcessID);
if (hProcess != NULL) {
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
// usage
int main()
{
kill("notepad");
}
我知道这已经很老了,但我觉得我应该解释一下2011年anwer的一些问题和不良做法。除非您需要,否则绝对没有理由可以用c ++编写c语言。不需要使用const char数组,因为std :: string :: c_str()已返回指向该字符串的指针。如您在我的代码段中所见...