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 th
You can test the process life by using
bool isProcessRunning(HANDLE process)
{
return WaitForSingleObject( process, 0 ) == WAIT_TIMEOUT;
}
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;
}
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.
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;
}