Reputation:
I'm using VS C++ 2010. I need to get program state but It seems when program says It stopped working my function isn't working. I need that for restarting program if It stops working.
My Code:
BOOL IsProcessRunning(DWORD pid)
{
HANDLE process = OpenProcess(SYNCHRONIZE, FALSE, pid);
DWORD ret = WaitForSingleObject(process, 0);
CloseHandle(process);
return ret == WAIT_TIMEOUT;
}
Upvotes: 0
Views: 601
Reputation: 612954
This code can never work. If the external process has stopped running, then OpenProcess
will fail because the process ended and the PID is no longer valid. And you don't check the value returned by OpenProcess
. Or the PID has been re-used and then you would have a handle to the wrong process.
To use WaitForSingleObject
in a reliable way, you need to get a handle to the process and hang on to it. Call OpenProcess
once, and then use that handle for all subsequent calls to WaitForSingleObject
. Call CloseHandle
only when you are finished dealing with that process.
However, your use of WaitForSingleObject
is simply not going to be useful for detecting that a program is not responding. In that case the call to OpenProcess
will succeed since the process still exists and is running. The call to WaitForSingleObject
returns WAIT_TIMEOUT
since the process is still running. After all, a hung process is still running.
So the entire premise of your code is wrong. A hung window (or indeed any window) can only exist in a running process! You will need to throw away the code that you have and instead simply call IsHungAppWindow
. You will need a window handle for the applications main window.
Upvotes: 3