建立進程並等待其退出

來源:互聯網
上載者:User

在命令列裡,你敲完一個命令後,一般是這個命令執行完畢後你才獲得控制台。在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)<br />{<br /> //Get a mutable version of the command line<br /> wchar_t* cmdLine = new wchar_t[commandLine.length() + 1];<br /> wcscpy_s(cmdLine, commandLine.length() + 1, commandLine.c_str());<br /> //Launch the process<br /> STARTUPINFOW startupInfo;<br /> PROCESS_INFORMATION pInfo;<br /> ::ZeroMemory(&startupInfo, sizeof(startupInfo));<br /> ::ZeroMemory(&pInfo, sizeof(pInfo));<br /> if (!CreateProcessW(NULL, cmdLine, NULL, NULL, false, 0, NULL, NULL, &startupInfo,<br /> &pInfo))<br /> {<br /> delete[] cmdLine;<br /> throw L"Error while executing " + appName + L": " + GetErrorMessage(GetLastError());<br /> }<br /> delete[] cmdLine;<br /> //Ok the process was created, wait for it to terminate.<br /> DWORD lastWait = 0;<br /> while ((lastWait = WaitForSingleObject(pInfo.hProcess, 50)) == WAIT_TIMEOUT)<br /> Application::Get().Yield();<br /> if (lastWait == WAIT_ABANDONED)<br /> throw std::wstring(L"The condition waiting on the termination of the .NET installer was abandoned.");<br /> //Get the exit code<br /> DWORD exitCode = 0;<br /> if (!GetExitCodeProcess(pInfo.hProcess, &exitCode))<br /> throw GetErrorMessage(GetLastError());<br /> //Clean up<br /> CloseHandle(pInfo.hProcess);<br /> CloseHandle(pInfo.hThread);<br /> //Return the exit code.<br /> return exitCode;<br />} 

 

下面是chrome裡面建立進程並擷取輸出的代碼:

bool GetAppOutput(const CommandLine& cl, std::string* output) {<br /> HANDLE out_read = NULL;<br /> HANDLE out_write = NULL;<br /> SECURITY_ATTRIBUTES sa_attr;<br /> // Set the bInheritHandle flag so pipe handles are inherited.<br /> sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);<br /> sa_attr.bInheritHandle = TRUE;<br /> sa_attr.lpSecurityDescriptor = NULL;<br /> // Create the pipe for the child process's STDOUT.<br /> if (!CreatePipe(&out_read, &out_write, &sa_attr, 0)) {<br /> NOTREACHED() << "Failed to create pipe";<br /> return false;<br /> }<br /> // Ensure we don't leak the handles.<br /> win::ScopedHandle scoped_out_read(out_read);<br /> win::ScopedHandle scoped_out_write(out_write);<br /> // Ensure the read handle to the pipe for STDOUT is not inherited.<br /> if (!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0)) {<br /> NOTREACHED() << "Failed to disabled pipe inheritance";<br /> return false;<br /> }<br /> // Now create the child process<br /> PROCESS_INFORMATION proc_info = { 0 };<br /> STARTUPINFO start_info = { 0 };<br /> start_info.cb = sizeof(STARTUPINFO);<br /> start_info.hStdOutput = out_write;<br /> // Keep the normal stdin and stderr.<br /> start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);<br /> start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);<br /> start_info.dwFlags |= STARTF_USESTDHANDLES;<br /> // Create the child process.<br /> if (!CreateProcess(NULL,<br /> const_cast<wchar_t*>(cl.command_line_string().c_str()),<br /> NULL, NULL,<br /> TRUE, // Handles are inherited.<br /> 0, NULL, NULL, &start_info, &proc_info)) {<br /> NOTREACHED() << "Failed to start process";<br /> return false;<br /> }<br /> // We don't need the thread handle, close it now.<br /> CloseHandle(proc_info.hThread);<br /> // Close our writing end of pipe now. Otherwise later read would not be able<br /> // to detect end of child's output.<br /> scoped_out_write.Close();<br /> // Read output from the child process's pipe for STDOUT<br /> const int kBufferSize = 1024;<br /> char buffer[kBufferSize];<br /> for (;;) {<br /> DWORD bytes_read = 0;<br /> BOOL success = ReadFile(out_read, buffer, kBufferSize, &bytes_read, NULL);<br /> if (!success || bytes_read == 0)<br /> break;<br /> output->append(buffer, bytes_read);<br /> }<br /> // Let's wait for the process to finish.<br /> WaitForSingleObject(proc_info.hProcess, INFINITE);<br /> CloseHandle(proc_info.hProcess);<br /> return true;<br />}<br /> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.