C++ TerminateProcess 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2443738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:30:23  来源:igfitidea点击:

C++ TerminateProcess function

c++windowsprocesstermination

提问by jemper

I've been searching examples for the Win32 API C++ function TerminateProcess()but couldn't find any.

我一直在搜索 Win32 API C++ 函数TerminateProcess() 的示例,但找不到任何示例。

I'm not that familiar with the Win32 API in general and so I wanted to ask if someone here who is better in it than me could show me an example for,

我一般对 Win32 API 不太熟悉,所以我想问这里是否有人比我更好,可以向我展示一个例子,

  • Retrieving a process handle by its PID required to terminate it and then call TerminateProcess with it.
  • 通过终止进程所需的 PID 检索进程句柄,然后使用它调用 TerminateProcess。

If you aren't familiar with C++ a C# equivalent would help too.

如果您不熟悉 C++,C# 等价物也会有所帮助。

回答by Don Reba

To answer the original question, in order to retrieve a process handle by its PID and call TerminateProcess, you need code like the following:

要回答原始问题,为了通过其 PID 检索进程句柄并调用 TerminateProcess,您需要如下代码:

BOOL TerminateProcessEx(DWORD dwProcessId, UINT uExitCode)
{
    DWORD dwDesiredAccess = PROCESS_TERMINATE;
    BOOL  bInheritHandle  = FALSE;
    HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
    if (hProcess == NULL)
        return FALSE;

    BOOL result = TerminateProcess(hProcess, uExitCode);

    CloseHandle(hProcess);

    return result;
}

Keep in mind that TerminateProcess does not allow its target to clean up and exit in a valid state. Think twice before using it.

请记住, TerminateProcess 不允许其目标清理并以有效状态退出。使用前请三思。