7.1. Terminating a Process Forcefully

Terminating a process in Windows using TerminateProcess() requires the process handle, which can be acquired using the process ID. The procedure uses these three functions:


Use the PID to acquire the process handle from an existing process

HANDLE OpenProcess(
    DWORD dwDesiredAccess,  // Flags to control access to the process object.
    BOOL  bInheritHandle,   // Inherit handle
    DWORD dwProcessId       // Process ID to access

Terminates the process and all of its threads using the process handle

BOOL TerminateProcess(
    HANDLE hProcess,    // A handle to the process to be terminated.
    UINT   uExitCode    // The exit code that the process will return

Release the process handle

BOOL CloseHandle(
    HANDLE hObject


  • Using function TerminateProcess() terminates the process immediately.

  • It does not do it gracefully.

  • It is equivalent to unplugging the power from your computer instead of using the shutdown procedure.

TerminateProcess() Template Code

Required Include Files

#include <windows.h>

Basic Usage

DWORD pid;
HANDLE process_handle;

pid = 99999;

process_handle = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, TRUE, pid);
TerminateProcess(process_handle, 0);


7.1.1. Task: Error Handling

Please create a file called lab7.1.c from the template C file for this assignment.

Your first task is to test the error handling.

  1. Add error handling to TerminateProcess() and CloseHandle()

  2. Execute the code using a PID of 99999. It should be an invalid PID.

  3. Verify that your program prints an error message with the PID.

Expected Output

Error terminating PID 99999.

7.1.2. Task: Terminate Process

Next, terminate a process using a valid process ID

  1. Start notepad.exe and add some text.

    1. Press the X button to close the windows and verify that the Save Dialog window displays. Press Cancel to close the dialog

  2. Open the Task Manager and locate the PID.

  3. Use your code to terminate the process using the PID.

  4. Verify that notepad closes without prompting the user to save the file

You can see that using TerminateProcess() closes an application in a way that is not safe. There are better shutdown methods that wait for the application to perform any cleanup code or to send a shutdown signal so the process can exit gracefully.