Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

  • Retrieving a process handle by its PID required to terminate it and then call TerminateProcess with it.

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

like image 927
jemper Avatar asked Mar 14 '10 20:03

jemper


People also ask

What is TerminateProcess?

1. Terminate is a term used to describe the process of stopping a running software program or permanently removing a program from a computer. Tip. In Windows you can terminate a process through the Task Manager. 2.

Which function is used to terminate the process?

The TerminateProcess function is used to unconditionally cause a process to exit. The state of global data maintained by dynamic-link libraries (DLLs) may be compromised if TerminateProcess is used rather than ExitProcess.


1 Answers

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.

like image 117
Don Reba Avatar answered Oct 13 '22 03:10

Don Reba