Terminate Win32 Process

Terminating a process means ending its execution and freeing its resources. However, terminating a process should be done with caution, as it may cause data loss or corruption, or leave the system in an inconsistent state. However, sometimes you need to do it anyway, for example to kill a misbehaving program.

One way to terminate a process is to use the TerminateProcess function from the Win32 API. This function takes two parameters: a handle to the process to be terminated, and an exit code for the process and its threads. The handle must have the PROCESS_TERMINATE access right, which can be obtained by calling the OpenProcess function with the same right. The exit code can be any value, and this is the value the system or other software retrieves later by calling the GetExitCodeProcess function.

The TerminateProcess function is used to unconditionally cause a process to exit, without giving it a chance to clean up its resources or notify other processes. This may result in memory leaks, file locks, or other problems. Therefore, this function should be used only as a last resort, when there is no other way to end a process.

Here is a fully functional function implementation that kills a process:

bool process::terminate(DWORD pid) {
        HANDLE hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, pid);
        if (hProcess) {
            return ::TerminateProcess(hProcess, 1);	// exit code is 1
        }
        return false;
    }


To contact me, send an email anytime or leave a comment below.