C语言 如何按名称杀死进程?(Win32 API)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7956519/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:02:18  来源:igfitidea点击:

How to kill processes by name? (Win32 API)

cwinapiapi

提问by dikidera

Basically, I have a program which will be launched more than once. So, there will be two or more processes launched of the program.

基本上,我有一个将多次启动的程序。因此,该程序将启动两个或多个进程。

I want to use the Win32 API and kill/terminate all the processes with a specific name.

我想使用 Win32 API 并使用特定名称杀死/终止所有进程。

I have seen examples of killing A process, but not multiple processes with the exact same name(but different parameters).

我见过杀死 A 进程的例子,但没有看到多个具有完全相同名称(但参数不同)的进程。

回答by masoud

Try below code, killProcessByName()will kill any process with name filename:

尝试下面的代码,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;
}

Note: The code is case sensitive to filename, you can edit it for case insensitive.

注意:代码区分大小写filename,您可以编辑不区分大小写。

回答by Jeremy Whitcher

I just ran into a similar problem. Here's what I came up with...

我刚刚遇到了类似的问题。这是我想出的...

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);    
   }
}

回答by Trey

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");
}

I know this is old but i feel as if i should explain some of the issues and bad practice with the 2011 anwer. There is absolutely no reasonfor you to be writing c in c++ unless you need to. The use of const char array is unnecessary as std::string::c_str() already returns a pointer to the string. As you can see in my snippet...

我知道这是旧的,但我觉得我应该用 2011 anwer 解释一些问题和不好的做法。这里是绝对没有理由让你用C编写C ++,除非你需要。不需要使用 const char 数组,因为 std::string::c_str() 已经返回指向字符串的指针。正如你在我的片段中看到的那样......

    - filename is no longer a const char, instead its a string because its native c++ and good practice
    - 文件名不再是一个常量字符,而是一个字符串,因为它的原生 C++ 和良好的实践
    - strcmp check is removed as there is no reason to compare string differences. Instead we check if they're equivalent
    - 删除 strcmp 检查,因为没有理由比较字符串差异。相反,我们检查它们是否相等
    - We append ".exe" to filename so you can type the process name without the .exe
    - 我们将“.exe”附加到文件名,以便您可以键入不带 .exe 的进程名称
除非强制要求,否则根本没有理由在 c++ 中编写 c。