Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill processes by name? (Win32 API)

Tags:

c

winapi

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).

like image 262
dikidera Avatar asked Oct 31 '11 16:10

dikidera


People also ask

How do I kill a process in win32?

Any thread calls the TerminateProcess function with a handle to the process. For console processes, the default console control handler calls ExitProcess when the console receives a CTRL+C or CTRL+BREAK signal.

How do I kill a process in Windows by name?

To Kill Process using Process/Image Name a) Type the following command into the run prompt, to kill only the one Process, and press Enter Key. For Example - To kill Notepad, run the command as, taskkill /IM notepad.exe /F , where /F is used to kill the process forcefully.

How do you kill a process in C++?

exit functionh>, terminates a C++ program. The value supplied as an argument to exit is returned to the operating system as the program's return code or exit code. By convention, a return code of zero means that the program completed successfully.


1 Answers

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.

like image 183
masoud Avatar answered Oct 24 '22 00:10

masoud