在进程中创建子进程是很常见的话题。常规的方法是用CreateProcess(),这个函数功能强大,使用起来也很方便。不过CreateProcess()或其他函数,如ShellExecuteEx(),在创建子进程后,并不等待子进程初始化完毕,而是立即返回。
通常你应该等子进程初始化完毕后再开始其它事情,特别是子进程有消息循环时。这可以通过函数WaitForInputIdle()实现。这个函数要求你提供子进程的句柄,CreateProcess()和ShellExecuteEx()都返回子进程的句柄。
WaitForInputIdle()优于sleep()。例如,sleep(3000)一定使进程睡3s。有时候多了,有时候少了。当sleep()结束时,子进程可能初始化完毕,也可能没有,但父进程都立即恢复执行。使用ForInputIdle(),当子进程初始化完毕后,父进程才继续执行。
ShellExecuteEx()也可以启动进程。不过ShellExecuteEx()常用在这样的场合,象打开pdf或txt等。即你不知道应用程序的名字,只知道文件名的时候。
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
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.