Подтвердить что ты не робот

Как получить код возврата подпроцесса

Каков метод получения возвращаемого значения от нереста подпроцесса в окнах? Похоже, что ShellExecute() проще использовать, чем CreateProcess(), но из чтения, которое я сделал до сих пор, не указано, как проверить возвращаемое значение порожденного процесса. Как это делается?

Спасибо, Энди

4b9b3361

Ответ 1

Чтобы получить код выхода процесса в Windows, вы можете использовать GetExitCodeProcess().

Пример приложения, который принимает идентификатор процесса в качестве аргумента и ждет пять секунд для его завершения, а затем получает код выхода:

int main(int a_argc, char** a_argv)
{
    int pid = atoi(*(a_argv + 1));

    HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE, pid);

    if (NULL != h)
    {
        WaitForSingleObject(h, 5000); // Change to 'INFINITE' wait if req'd
        DWORD exit_code;
        if (FALSE == GetExitCodeProcess(h, &exit_code))
        {
            std::cerr << "GetExitCodeProcess() failure: " <<
                GetLastError() << "\n";
        }
        else if (STILL_ACTIVE == exit_code)
        {
            std::cout << "Still running\n";
        }
        else
        {
            std::cout << "exit code=" << exit_code << "\n";
        }
        CloseHandle(h);
    }
    else
    {
        std::cerr << "OpenProcess() failure: " << GetLastError() << "\n";
    }

    return 0;
}

Ответ 2

Вот полный код, основанный на http://msdn.microsoft.com/en-us/library/windows/desktop/ms682512%28v=vs.85%29.aspx и решении hmjd:

#include <stdio.h>
#include <Windows.h>

int main()
{
  const size_t stringSize = 1000;
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  DWORD exit_code;
  char commandLine[stringSize] = "C:\\myDir\\someExecutable.exe param1 param2";
  WCHAR wCommandLine[stringSize];
  mbstowcs (wCommandLine, commandLine, stringSize);

  ZeroMemory( &si, sizeof(si) );
  si.cb = sizeof(si);
  ZeroMemory( &pi, sizeof(pi) );

  // Start the child process. 
  if( !CreateProcess( NULL,   // No module name (use command line)
      wCommandLine,   // Command line
      NULL,           // Process handle not inheritable
      NULL,           // Thread handle not inheritable
      FALSE,          // Set handle inheritance to FALSE
      0,              // No creation flags
      NULL,           // Use parent environment block
      NULL,           // Use parent starting directory 
      &si,            // Pointer to STARTUPINFO structure
      &pi )           // Pointer to PROCESS_INFORMATION structure
  ) 
  {
      printf("CreateProcess failed (%d).\n", GetLastError() );
      return -1;
  }

  // Wait until child process exits.
  WaitForSingleObject( pi.hProcess, INFINITE );

  GetExitCodeProcess(pi.hProcess, &exit_code);

  printf("the execution of: \"%s\"\nreturns: %d\n", commandLine, exit_code);

  // Close process and thread handles. 
  CloseHandle( pi.hProcess );
  CloseHandle( pi.hThread );
  return 0;
}

(работает как консольное приложение VS2005 в Windows XP)