您的位置:首页 > 其它

创建进程并等待其退出

2009-12-11 16:51 363 查看
在命令行里,你敲完一个命令后,一般是这个命令执行完毕后你才获得控制台。在360的软件管家里面也有这种效果(软件升级时)。如果你要实现这种效果,一般就需要创建进程并等待其退出的函数。这个函数实现的关键是CreateProcessW和WaitForSingleObject两个函数,网上也有这样的代码。下面是一个叫做Eraser的开源工程里面的一段代码,这个里面也有一些其他有用的代码,大家可以参考参考:

http://eraser.heidi.ie/trac/browser/trunk/eraser6/Installer/Bootstrapper/Bootstrapper.cpp?rev=1278



int CreateProcessAndWait(const std::wstring& commandLine, const std::wstring& appName)
{
        //Get a mutable version of the command line
        wchar_t* cmdLine = new wchar_t[commandLine.length() + 1];
        wcscpy_s(cmdLine, commandLine.length() + 1, commandLine.c_str());
        //Launch the process
        STARTUPINFOW startupInfo;
        PROCESS_INFORMATION pInfo;
        ::ZeroMemory(&startupInfo, sizeof(startupInfo));
        ::ZeroMemory(&pInfo, sizeof(pInfo));
        if (!CreateProcessW(NULL, cmdLine, NULL, NULL, false, 0, NULL,  NULL, &startupInfo,
                &pInfo))
        {
                delete[] cmdLine;
                throw L"Error while executing " + appName + L": " + GetErrorMessage(GetLastError());
        }
        delete[] cmdLine;
        //Ok the process was created, wait for it to terminate.
        DWORD lastWait = 0;
        while ((lastWait = WaitForSingleObject(pInfo.hProcess, 50)) == WAIT_TIMEOUT)
                Application::Get().Yield();
        if (lastWait == WAIT_ABANDONED)
                throw std::wstring(L"The condition waiting on the termination of the .NET installer was abandoned.");
        //Get the exit code
        DWORD exitCode = 0;
        if (!GetExitCodeProcess(pInfo.hProcess, &exitCode))
                throw GetErrorMessage(GetLastError());
        //Clean up
        CloseHandle(pInfo.hProcess);
        CloseHandle(pInfo.hThread);
        //Return the exit code.
        return exitCode;
}




下面是chrome里面创建进程并获取输出的代码:

bool GetAppOutput(const CommandLine& cl, std::string* output) {
  HANDLE out_read = NULL;
  HANDLE out_write = NULL;
  SECURITY_ATTRIBUTES sa_attr;
  // Set the bInheritHandle flag so pipe handles are inherited.
  sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
  sa_attr.bInheritHandle = TRUE;
  sa_attr.lpSecurityDescriptor = NULL;
  // Create the pipe for the child process's STDOUT.
  if (!CreatePipe(&out_read, &out_write, &sa_attr, 0)) {
    NOTREACHED() << "Failed to create pipe";
    return false;
  }
  // Ensure we don't leak the handles.
  win::ScopedHandle scoped_out_read(out_read);
  win::ScopedHandle scoped_out_write(out_write);
  // Ensure the read handle to the pipe for STDOUT is not inherited.
  if (!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0)) {
    NOTREACHED() << "Failed to disabled pipe inheritance";
    return false;
  }
  // Now create the child process
  PROCESS_INFORMATION proc_info = { 0 };
  STARTUPINFO start_info = { 0 };
  start_info.cb = sizeof(STARTUPINFO);
  start_info.hStdOutput = out_write;
  // Keep the normal stdin and stderr.
  start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  start_info.dwFlags |= STARTF_USESTDHANDLES;
  // Create the child process.
  if (!CreateProcess(NULL,
                     const_cast<wchar_t*>(cl.command_line_string().c_str()),
                     NULL, NULL,
                     TRUE,  // Handles are inherited.
                     0, NULL, NULL, &start_info, &proc_info)) {
    NOTREACHED() << "Failed to start process";
    return false;
  }
  // We don't need the thread handle, close it now.
  CloseHandle(proc_info.hThread);
  // Close our writing end of pipe now. Otherwise later read would not be able
  // to detect end of child's output.
  scoped_out_write.Close();
  // Read output from the child process's pipe for STDOUT
  const int kBufferSize = 1024;
  char buffer[kBufferSize];
  for (;;) {
    DWORD bytes_read = 0;
    BOOL success = ReadFile(out_read, buffer, kBufferSize, &bytes_read, NULL);
    if (!success || bytes_read == 0)
      break;
    output->append(buffer, bytes_read);
  }
  // Let's wait for the process to finish.
  WaitForSingleObject(proc_info.hProcess, INFINITE);
  CloseHandle(proc_info.hProcess);
  return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: