如何获得子流程的返回代码

And*_*nga 13 c++ winapi

从Windows中生成子流程获取返回值的方法是什么?它看起来ShellExecute()比使用起来更简单CreateProcess(),但是从我到目前为止所做的阅读中,都没有说明如何检查衍生过程的返回值.怎么做的?

谢谢,安迪

hmj*_*mjd 22

要获取Windows上进程的退出代码,您可以使用GetExitCodeProcess().

接受进程id作为参数的示例应用程序,等待五秒钟完成,然后获取其退出代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.这就是我想要的.看起来我必须使用CreateProcess()来启动这个东西.该函数填充了一个PROCESS_INFORMATION结构,该结构具有我需要用于GetExitCodeProcess()的HANDLE. (3认同)

ces*_*nec 7

这是一个完整的代码,基于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's environment block
      NULL,           // Use parent's 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;
}
Run Code Online (Sandbox Code Playgroud)

(在Windows XP中作为VS2005控制台应用程序运行)