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

转自:http://blog.csdn.net/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"));


你可能感兴趣的:(thread,Security,null,inheritance,attributes)