How to kill processes by name? (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.

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

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


Solution 1:

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

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

Solution 2:

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