Using TerminateProcess in C++

The terminateprocess function is a function in the Windows API that is used to end a specified process.

Its prototype is as follows:

Terminate the process identified by hProcess using the exit code specified by uExitCode.

Explanation of parameters:

  1. hProcess: Handle to the process to be terminated. Can be obtained using the OpenProcess function.
  2. Exit code: The process’s exit code.

The sample code is shown below:

#include <windows.h>

int main()
{
    // 打开要终止的进程
    HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, 1234); // 1234为要终止的进程ID
    if (hProcess == NULL)
    {
        printf("打开进程失败\n");
        return 1;
    }

    // 终止进程
    BOOL result = TerminateProcess(hProcess, 0); // 0为进程的退出码
    if (result == 0)
    {
        printf("终止进程失败\n");
        return 1;
    }

    // 关闭进程句柄
    CloseHandle(hProcess);

    return 0;
}

Please note:

  1. Administrator privileges are required to use the terminateprocess function.
  2. Terminating other processes may result in system instability, so please consider carefully before using.
bannerAds