Ryan
Ryan

Reputation: 985

Getting Process Information from Process Handle

I need to get the PROCESS_INFORMATION of an external process for use in my application, I have the process handle and process ID, but I don't know how to go about getting the PROCESS_INFORMATION out of that.

I'm using C++(11), Visual Studio 2012, running on Windows. Any help would be greatly appreciated.

Upvotes: 4

Views: 8622

Answers (3)

Hans Passant
Hans Passant

Reputation: 941465

PROCESS_INFORMATION is filled by CreateProcess(). That ship has sailed; the process was already started.

Let's focus on what you really want to do. To find out if a process has terminated, first use OpenProcess() to obtain a handle to the process. You'll need the PID, which you already have. Then WaitForSingleObject() will tell you if it is terminated. Pass INFINITE for the 2nd argument to block until the process terminates. Pass 0 if you want to poll. Finally, use CloseHandle() to clean up.

Upvotes: 6

Remy Lebeau
Remy Lebeau

Reputation: 596246

PROCESS_INFORMMATION provides 4 pieces of information:

HANDLE hProcess
HANDLE hThread
DWORD dwProcessID
DWORD dwThreadID

You say you already have two of those values - the Process Handle and Process ID. So that just leaves the Thread Handle and Thread ID. Those belong to the first thread created for the process. You can use CreateToolhelp32Snapshot(), Thread32First(), and Thread32Next() to enumerate the running threads looking for Thread IDs that belong to a given Process ID, and then use OpenThread() to get the Thread Handle of a given Thread ID. The tricky part is identifying which Thread ID is the first thread. That information is not readily available outside of CreateProcess().

Upvotes: 1

Carey Gregory
Carey Gregory

Reputation: 6846

The information you need can be obtained with the CreateToolhelp32Snapshot function since it returns both the process ID and the parent process ID. An example of its use can be found here.

Upvotes: 0

Related Questions