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:
- hProcess: Handle to the process to be terminated. Can be obtained using the OpenProcess function.
- 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:
- Administrator privileges are required to use the terminateprocess function.
- Terminating other processes may result in system instability, so please consider carefully before using.