views:

144

answers:

3

I need to check if a process with a given HANDLE is still runnning, I tried to do it using the following code however it always returns at the second return false, even if the process is running.

bool isProcessRunning(HANDLE process)
{
    if(process == INVALID_HANDLE_VALUE)return false;

    DWORD exitCode;
    if(GetExitCodeProcess(process, &exitCode) != 0)
        return false;//always returns here

    return GetLastError() == STILL_ACTIVE;//still running
}
+3  A: 

You can test the process life by using

bool isProcessRunning(HANDLE process)
{
   return WaitForSingleObject( process, 0 ) == WAIT_TIMEOUT;
}
decasteljau
Just needed to add a check for the INVALID_HANDLE_VALUE since that reported the process was running when it wasn't even valid :)
Fire Lancer
APIs like WaitForSingleObject should never return INVALID_HANDLE_VALUE if you have a process handle open, even if it is terminated. The handle and underlying object must stay open until explicitly closed by the referencing processes (or those processes are terminated). Are you sure you're not trying to call it on the process ID and not a handle?
Chris Smith
I meant a check before the WaitForSingleObject, in the event the process hadn't yet been created, so the handle was still at the value I initialised it to, ie INVALID_HANDLE_VALUE, since passing INVALID_HANDLE_VALUE to WaitForSingleObject always times out (ie INVALID_HANDLE_VALUEis never in a signaled state it seems).
Fire Lancer
+2  A: 

http://msdn.microsoft.com/en-us/library/ms683189%28VS.85%29.aspx

Return Value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

dalle
the _only_ real answer here.
gimpf
A: 

You can use EnumProcesses() to get all processes running on Windows. Something like:

bool IsProcessRunning(int pid)
{
unsigned long processes[2048];
unsigned long num_proc = 0;
unsigned long needed = 0;

// assume that 2048 processes are enought
if (EnumProcesses(processes, sizeof(processes), &needed))
num_proc = needed / sizeof(DWORD);

for (int i = 0; i < num_proc; i++)
if (processes[i] == pid)
return true;

return false;
}

Flavius Suciu
unnecessarily complicated
gimpf