Q: How can I kill a process?
A: There are different ways depending whether the process will be killed from inside or outside. For killing a process from inside the function 'ExitProcess()' can be used.
Code:
::ExitProcess(0); // Zero is the exit code in this example
This will close the actual process. It is the preferred method to end a process and provides a clean shutdown of the process. Note that this function should not be called from inside a DLL since this could lead to unexpected application or system errors.
To kill a process from outside a 'WM_CLOSE' message should be sent to its primary thread. If the process was created with 'CreateProcess()' the 'PROCESS_INFORMATION' structure contains the ID of the primary thread which in turn can be used with 'PostThreadMessage()'...
Code:
::PostThreadMessage(piProcessInfo.dwThreadId, WM_CLOSE, 0, 0);
This (unfortunately) will only work if the primary thread of the process has created a message queue otherwise 'PostThreadMessage()' will fail. In this case the only possibility is to force the process to close by a call to 'TerminateProcess()'. Therefore a combination of 'PostThreadMessage()', 'WaitForSingleObject()' and 'TerminateProcess()' should be used as follows:
Code:
::PostThreadMessage(piProcessInfo.dwThreadId, WM_CLOSE, 0, 0);
::WaitForSingleObject(piProcessInfo.hProcess, 1000);
// Check exit code
DWORD dwExitCode = 0;
::GetExitCodeProcess(piProcessInfo.hProcess, &dwExitCode);
if(dwExitCode == STILL_ACTIVE)
{
// Process did not terminate -> force it
::TerminateProcess(piProcessInfo.hProcess, 0); // Zero is the exit code
// in this example
}
'TerminateProcess()' has some drawbacks which should be considered. It causes all threads within the process to terminate, and causes the process to exit, but DLLs attached to the process are not notified that the process is terminating. Additionally child processes of the terminating process will not be terminated. Therefore 'TerminateProcess()' should only be used in extreme circumstances.
There exists a knowledge base article which also covers the topic of a 'clean' termination of a process.