在進程中建立子進程是很常見的話題。常規的方法是用CreateProcess(),這個函數功能強大,使用起來也很方便。不過CreateProcess()或其他函數,如ShellExecuteEx(),在建立子進程後,並不等待子進程初始化完畢,而是立即返回。
通常你應該等子進程初始化完畢後再開始其它事情,特別是子進程有訊息迴圈時。這可以通過函數WaitForInputIdle()實現。這個函數要求你提供子進程的控制代碼,CreateProcess()和ShellExecuteEx()都返回子進程的控制代碼。
WaitForInputIdle()優於sleep()。例如,sleep(3000)一定使進程睡3s。有時候多了,有時候少了。當sleep()結束時,子進程可能初始化完畢,也可能沒有,但父進程都立即恢複執行。使用ForInputIdle(),當子進程初始化完畢後,父進程才繼續執行。
ShellExecuteEx()也可以啟動進程。不過ShellExecuteEx()常用在這樣的場合,象開啟pdf或txt等。即你不知道應用程式的名字,只知道檔案名稱的時候。
// Creates a child process and waits until the child process finishes initialization
STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;
TCHAR szCommandLine[] = _T(//"notepad.exe//");
BOOL bSuccess = CreateProcess(NULL, szCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (bSuccess)
{
::WaitForInputIdle (pi.hProcess, 5000L);
// close the handle if no longer used
::CloseHandle(pi.hProcess);
// do whatever you want to do
//HWND hBBBWnd = ::FindWindow(NULL, strBBBWindowName);
// ... ...
}簡單的講就是: 父進程建立子進程後 要先確定子進程初始化好了後才能使用子進程 。那麼有什麼方法可以讓父進程知道子進程已經準備好了呢 》?那就是父進程調用waitForInputIdle( 子進程id, 逾時),如果子進程沒初始化好 。那麼父進程將懸掛。知道 逾時或子進程準備好。一下內容摘自msdn:WaitForInputIdle
The WaitForInputIdle function waits until the given process is waiting for user input with no input pending, or until the time-out interval has elapsed.
The WaitForInputIdle function only works with GUI applications. If a console application calls the function, it returns immediately, with no wait.
DWORD WaitForInputIdle( HANDLE hProcess, // handle to process DWORD dwMilliseconds // time-out interval in milliseconds);
Parameters
-
hProcess
-
Handle to the process.
-
dwMilliseconds
-
Specifies the time-out interval, in milliseconds. If
dwMilliseconds is INFINITE, the function does not return until the process is idle.
Return Values
The following table shows the possible return values:
| Value |
Meaning |
| 0 |
The wait was satisfied successfully. |
| WAIT_TIMEOUT |
The wait was terminated because the time-out interval elapsed. |
| 0xFFFFFFFF |
An error occurred. To get extended error information, use the GetLastError function. |
Remarks
The WaitForInputIdle function enables a thread to suspend its execution until a specified process has finished its initialization and is waiting for user input with no input pending. This can be useful for synchronizing a parent process and a newly created child process. When a parent process creates a child process, the CreateProcess function returns without waiting for the child process to finish its initialization. Before trying to communicate with the child process, the parent process can use WaitForInputIdle to determine when the child's initialization has been completed. For example, the parent process should use WaitForInputIdle before trying to find a window associated with the child process.
The WaitForInputIdle function can be used at any time, not just during application startup.