Fire Lancer
Fire Lancer

Reputation: 30165

Detecting if a process is still running

I need to check if a process with a given HANDLE is still running, 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
}

Upvotes: 6

Views: 7161

Answers (4)

KymikoLoco
KymikoLoco

Reputation: 1503

I know this is a bit late, but your code should read like this if you want the results you expect.

bool isProcessRunning(HANDLE process)
{    
    DWORD exitCodeOut;

    // GetExitCodeProcess returns zero on failure
    if( GetExitCodeProcess( process, &exitCodeOut ) == 0 )
    {
        // Optionally get the error
        // DWORD error = GetLastError();
        return false;
    }
    // Return if the process is still active
    return exitCodeOut == STILL_ACTIVE;
}

If you only have the process ID (PID), this snippet will work (sans error checking):

bool isProcessRunning(DWORD processID)
{    
    if( HANDLE process = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID ) )
    {
        DWORD exitCodeOut;
        // GetExitCodeProcess returns zero on failure
        if( GetExitCodeProcess( process, &exitCodeOut ) != 0 )
        {
            // Return if the process is still active
            return exitCodeOut == STILL_ACTIVE;
        }
    }
    return false;
}

Upvotes: 2

Flavius Suciu
Flavius Suciu

Reputation: 179

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;  
}

Upvotes: 1

dalle
dalle

Reputation: 18527

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.

Upvotes: 3

decasteljau
decasteljau

Reputation: 8043

You can test the process life by using

bool isProcessRunning(HANDLE process)
{
   return WaitForSingleObject( process, 0 ) == WAIT_TIMEOUT;
}

Upvotes: 9

Related Questions