Detecting if a process is still running

后端 未结 4 2033
花落未央
花落未央 2021-01-01 04:01

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

相关标签:
4条回答
  • 2021-01-01 04:43

    You can test the process life by using

    bool isProcessRunning(HANDLE process)
    {
       return WaitForSingleObject( process, 0 ) == WAIT_TIMEOUT;
    }
    
    0 讨论(0)
  • 2021-01-01 04:44

    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;
    }
    
    0 讨论(0)
  • 2021-01-01 05:05

    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.

    0 讨论(0)
  • 2021-01-01 05:08

    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;  
    }
    
    0 讨论(0)
提交回复
热议问题