Dariusz
Dariusz

Reputation: 22241

Check for a process previously started by the application always returns process alive

I am creating a process with CreateProcess:

The handle the the process is closed while it continues its execution.

Then I am checking the process state by getting the handle for process with given PID:

HANDLE HProcess = OpenProcess( 
       PROCESS_QUERY_INFORMATION , TRUE, task->taskPid);

Edit: Yes, I am checking whether the returned process is really the process I queried for:

if ( ( HProcess != NULL ) && ( GetProcessId(HProcess) != requestedPid ) )

Regardless of whether the created process is really running or not, I am getting a valid handle to the process. If I restart my application, the check code works properly. I suspect that the handle is somehow buffered, or the created process is in the same group - but I can't seem to find any information about it in the documentation.

Upvotes: 1

Views: 287

Answers (2)

Harry Johnston
Harry Johnston

Reputation: 36318

There is no guarantee that successfully opening a handle to a process means that the process is still running. So the behaviour you're describing is unsurprising.

Once you've opened a handle, you can easily check whether the process has finished:

DWORD dw = WaitForSingleObject(handle, 0);
if (dw == WAIT_OBJECT_0)
{
    // Process has exited
}

However, your approach is flawed to begin with, because you have no way of telling whether the process ID has been reused. Instead of storing the process ID, store the process handle returned from CreateProcess, and use it to test for process exit as shown.

Upvotes: 1

Dariusz
Dariusz

Reputation: 22241

While this is not an answer, it does work as a workaround:

Having a valid handle, one can check if the process has finished with:

DWORD exitCode = 0;
GetExitCodeProcess(HProcess, &exitCode);
if (exitCode == STILL_ACTIVE ) {
  //task alive (or exited with STILL_ACTIVE :( )
} else {
  //task exited with code exitCode
}

Upvotes: 0

Related Questions