I am developing a Windows console application in C . I need my program to do some operations on another process which I don't have any control over.
But, I have some doubts about a case where the target process might get terminated for some reason (by Task Manager, etc). Is it safe to use a handle to a process which is already terminated?
Note : I stop my operations if one of the functions fails.
HANDLE hProcess = OpenProcess(pid);
if( hProcess != NULL )
{
// Lets suppose process is terminated here
/* Some operations on process using returned handle*/
}
CodePudding user response:
Kernel objects in Windows are reference-counted, with references being represented as handles to objects. Client code can create kernel objects and receive an initial reference (e.g. CreateProcess
), increment the reference count on an existing object (e.g. OpenProcess
, or DuplicateHandle
), and decrement the reference count (CloseHandle
). As long as you hold on to a HANDLE
, the object referenced by that HANDLE
is kept alive.
In case of a process object, that object is valid at least as long as you hold a reference (HANDLE
) to it. The fact that a process has been terminated is observable, but doesn't otherwise invalidate or destroy the process object if there are any outstanding references to it.
Specifically this means that you can perform any operations you'd do with a "live" process (one for which the OS is still scheduling threads to execute), such as WaitForSingleObject
. In addition you can call GetExitCodeProcess
and that call won't return STILL_ACTIVE
.
Barring a call to CloseHandle
, you are now a stakeholder that has a say in the demise of the process object. It won't go away unless you sign it off. A corollary of this is that you now also control the validity of the PID. It's tied to the process' lifetime, and as long as you hold a reference to it by way of a HANDLE
, that PID won't get reused for another process.
In summary, as long as you hold on to a (process) HANDLE
you can do whatever.