天天看點

建立程序并等待其退出

在指令行裡,你敲完一個指令後,一般是這個指令執行完畢後你才獲得控制台。在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;

}

繼續閱讀