使用CreateProcess创建新的process 并返回process运行结束返回值

本文介绍了如何使用C++通过CreateProcess函数创建新进程,并在新进程结束后获取其退出状态码。

转自:http://blog.youkuaiyun.com/zgl7903/article/details/5975284

转载这篇主要是记住:获得create的新进程运行结束时的返回值的方法

如下:

#include <malloc.h>

DWORD run_Execute(LPCTSTR lpszFile, LPCTSTR lpszParam)
{
  DWORD               exitCode = 0;
  PROCESS_INFORMATION pInfo = {0};
  STARTUPINFO         sInfo = {0};
  sInfo.cb              = sizeof(STARTUPINFO);
  sInfo.wShowWindow     = SW_SHOW;
  
  int nCmdLen = (_tcslen(lpszFile) + _tcslen(lpszParam) + 2) * sizeof(TCHAR);
  LPTSTR lpszCmd = (LPTSTR)_alloca(nCmdLen);
  memset(lpszCmd, 0, nCmdLen);
  _tcscpy(lpszCmd, lpszFile);
  if(lpszParam)
  {
    _tcscat(lpszCmd, _T(" "));
    _tcscat(lpszCmd, lpszParam);
  }

  if(CreateProcess(
    NULL,      //LPCTSTR lpApplicationName, // pointer to name of executable module
    lpszCmd,   //LPTSTR lpCommandLine,  // pointer to command line string
    NULL,      //LPSECURITY_ATTRIBUTES lpProcessAttributes,  // process security attributes
    NULL,      //LPSECURITY_ATTRIBUTES lpThreadAttributes,   // thread security attributes
    FALSE,     //BOOL bInheritHandles,  // handle inheritance flag
    0,         //DWORD dwCreationFlags, // creation flags
    NULL,      //LPVOID lpEnvironment,  // pointer to new environment block
    NULL,      //LPCTSTR lpCurrentDirectory,   // pointer to current directory name
    &sInfo,    //LPSTARTUPINFO lpStartupInfo,  // pointer to STARTUPINFO
    &pInfo))    //LPPROCESS_INFORMATION lpProcessInformation  // pointer to PROCESS_INFORMATION
  {
    // Wait until child process exits.
    WaitForSingleObject( pInfo.hProcess, INFINITE );
   
    if (GetExitCodeProcess(pInfo.hProcess, &exitCode))
    {
      TRACE( _T("Exit code = %d/n"), exitCode);
    }
    else 
    {      
      TRACE( _T("GetExitCodeProcess() failed: %ld/n"), GetLastError());
      ASSERT(0);
    }

    // Close process and thread handles. 
    CloseHandle( pInfo.hProcess );
    CloseHandle( pInfo.hThread );
  } 
  else
  {
    TRACE( _T("CreateProcess() failed: %ld/n"), GetLastError());
    ASSERT(0);
  }

  return exitCode;
}

//测试示例
run_Execute(_T("notepad.exe"), _T("c://temp//aa.txt"));


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值