C++ TerminateProcess function
Asked Answered
A

1

14

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.

Aquileia answered 14/3, 2010 at 20:54 Comment(5)
Are you just looking for this WINAPI function OpenProcess msdn.microsoft.com/en-us/library/ms684320%28VS.85%29.aspx ? Putting this together with TerminateProcess shouldn't be too difficult.Fulgurating
No, I want to terminate a running process. That is why I have mentioned that I have to retrieve the PID of it first.Aquileia
When someone gives you a link, read it. Don't just assume from the name what it does. In fact, OpenProcess creates a process handle, given a PID, which is exactly what you asked for. @Charles: That should be an answer instead of a comment.Clevie
@Ben Voigt: Evidently it's not the whole answer as the last comment suggest that we need to retrieve the PID from somewhere. @jemper: Which process do you want to terminate? How are you identifying it if not by PID?Fulgurating
Since you want to terminate a process you didn't start, the first thing I'd ask to give you an answer is how you plan to locate such process. Are you looking for a given executable, or will you show the processes and ask the user, or is it a process that opened a given file, etc? And what if multiple processes fit the pattern?Lamebrain
A
25

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.

Achorn answered 15/3, 2010 at 4:13 Comment(4)
How can I get the process's PID?Nmr
What kind of identifier do you have for the process you want a PID for?Achorn
This does not have to be unique. You might have several instances of an executable running at the same time. You can use EnumProcesses to get all instances of a process with a given name or apply some additional selection criteria.Achorn
Beware that this would return immediately. While dying process may still hold some locks for some time. You may need to add a loop with GetExitCodeProcess to ensure that the process has already died.Investigator

© 2022 - 2024 — McMap. All rights reserved.