Loading color scheme

How to kill process by name in Windows using WinAPI?

Sometimes you may need to terminate (kill) a process in Windows. Why may you need this? For example, you have a kiosk and you need some application to be constantly running (the Kiosk GUI), but this application is written not perfectly, it hangs. You cannot make it work better, because it's not you who wrote it. You can write a small helper application that will be checking the status of an application, say, by sending some messages to its window. And if the application window does not respond, your tiny app will just kill the GUI app and restart it.

Leaving sending messages and re-launching applications out of the scope of this small article, let's find out how to actually kill the application. 

This sample code will effectively kill the application named "guiapp.exe". You can use it to kill any process. Just do not forget that you cannot kill a process that is running under the Administrator account while your process is running from User account. This may happen when the target process is elevated and yours not. Also, keep in mind the children processes (if any) are not terminated automatically (as in Linux). In Windows, you have to terminate children processes explicitly. 

#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("guiapp.exe");
    return 0;
}
Get all interesting articles to your inbox
Please wait