Microsoft Learn

Documentation

TerminateProcess Function

The TerminateProcess function terminates the calling process and any threads created by the process.

Syntax


BOOL TerminateProcess(
  [in] HANDLE hProcess,
  [in] UINT   uExitCode
);
                

Parameters

hProcess [in]
A handle to the process to be terminated. The handle must have the PROCESS_TERMINATE access right.
uExitCode [in]
The exit code for the process. Use the function `ExitProcess` to specify the exit code for the current process.

Return Value

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The TerminateProcess function is used to terminate a specified process. This function is typically used by system administrators or other processes that need to forcefully stop a misbehaving application.

When a process is terminated by TerminateProcess, the system does not run the process's termination handlers or perform any of the normal cleanup that occurs when a process terminates gracefully. This means that resources such as open files, memory allocations, and mutexes may not be released properly.

Use this function with caution, as it can lead to data loss or corruption if not used appropriately. For terminating the current process, it is recommended to use the ExitProcess function.

Example

The following example demonstrates how to terminate another process using its process ID:


#include <windows.h>
#include <iostream>

int main() {
    DWORD processId = 1234; // Replace with the actual process ID
    HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, processId);

    if (hProcess == NULL) {
        std::cerr << "Failed to open process. Error code: " << GetLastError() << std::endl;
        return 1;
    }

    if (TerminateProcess(hProcess, 0xDEADBEEF)) {
        std::cout << "Process terminated successfully." << std::endl;
    } else {
        std::cerr << "Failed to terminate process. Error code: " << GetLastError() << std::endl;
    }

    CloseHandle(hProcess);
    return 0;
}
                

Requirements

Minimum supported client Windows XP
Minimum supported server Windows Server 2003
Header Winternl.h (include Windows.h)
Library Kernel32.lib
DLL Kernel32.dll

See Also