Process Termination
The TerminateProcess function ends a process and all of its threads.
Note: Terminating a process abruptly can cause resource leaks. Use with caution.
Syntax
BOOL TerminateProcess(
HANDLE hProcess,
UINT uExitCode
);
Parameters
| Parameter | Type | Description |
|---|---|---|
hProcess |
HANDLE | Handle to the process to be terminated. The handle must have the PROCESS_TERMINATE access right. |
uExitCode |
UINT | Exit code to be reported to the system. Typically, 0 for success. |
Return Value
Returns a nonβzero value if the function succeeds; otherwise, it returns 0. Call GetLastError for extended error information.
Remarks
- The function forces the termination of all threads in the process; there is no chance for cleanup.
- If the process has a registered
CtrlHandler, it will not receive notification. - Terminating a critical system process can lead to system instability.
Example
#include <windows.h>
#include <stdio.h>
int main(void) {
DWORD pid = 1234; // Replace with the target process ID
HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
if (hProc == NULL) {
printf("OpenProcess failed: %lu\n", GetLastError());
return 1;
}
if (!TerminateProcess(hProc, 0)) {
printf("TerminateProcess failed: %lu\n", GetLastError());
CloseHandle(hProc);
return 1;
}
printf("Process %lu terminated successfully.\n", pid);
CloseHandle(hProc);
return 0;
}