user3816764
user3816764

Reputation: 489

How do I get a handle to a process in Visual C++?

I opened up a process using CreateProcess (calc.exe in this case).

I passed the parameters to createProcess:

L"<path to calc>",
NULL,
NULL,
NULL,
false,
NORMAL_PRIORITY_CLASS,
NULL,
NULL,
&<startupInfo struct memset to 0>
&<procInfo struct memset to 0>

I'd like to be able to kill the process, open threads in that process, etc. I know the calls to do so but they require handles, which I don't have.

Is there a way to automatically open a handle to a child process when spawning it, or something else?

I was thinking th e'inherit handles' parameter in CreateProcess but that doesn't seem quite right.

Upvotes: 1

Views: 102

Answers (1)

Roger Rowland
Roger Rowland

Reputation: 26259

The final argument you pass to CreateProcess is a pointer to a PROCESS_INFORMATION structure (that's your procInfo variable).

On successful return from CreateProcess, that structure will be populated with the HANDLE's you need. Specifically, it will contain the following:

hProcess

A handle to the newly created process. The handle is used to specify the process in all functions that perform operations on the process object.

hThread

A handle to the primary thread of the newly created process. The handle is used to specify the thread in all functions that perform operations on the thread object.

dwProcessId

A value that can be used to identify a process. The value is valid from the time the process is created until all handles to the process are closed and the process object is freed; at this point, the identifier may be reused.

dwThreadId

A value that can be used to identify a thread. The value is valid from the time the thread is created until all handles to the thread are closed and the thread object is freed; at this point, the identifier may be reused.

As MSDN says:

Handles in PROCESS_INFORMATION must be closed with CloseHandle when they are no longer needed.

Upvotes: 3

Related Questions