0

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

1 Answers1

3

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thank you !, I checked IsHungAppWindow. I'm new in C++ so I have to ask. How can I get Hwnd from other app ? –  Sep 25 '15 at 11:22
  • http://stackoverflow.com/questions/1888863/how-to-get-main-window-handle-from-process-id – David Heffernan Sep 25 '15 at 11:28