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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With