jemper
jemper

Reputation: 177

C++ TerminateProcess function

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

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,

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

Upvotes: 14

Views: 48320

Answers (1)

Don Reba
Don Reba

Reputation: 14061

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

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.

Upvotes: 25

Related Questions