In many situations an application will start another application to perform some task (such as processing a file or connecting to a network), and will need to wait until the second application has completed the task. Further, the application will need to determine if the second application completed the task successfully or not. This can be achieved by calling the WaitForSingleObject function and using the process's exit code. Process kernel objects can be in one of two states signaled and non-signaled. A process kernel object that represents a running process is non-signaled. The process kernel object becomes signaled when the process terminates. The WaitForSingleObject (Table 5.3) can be passed a process kernel object, and the function call will block (that is, not return) until the process kernel object becomes signaled (which happens when the process itself terminates). The code in Listing 5.3 creates a process and then calls WaitForSingleObject, passing in the process kernel object handle and the amount of time to wait. (In this case, INFINITE causes WaitForSingleObject to block until the process terminates, regardless of how long this may be.) The call to WaitForSingleObject will not return until the process started by CreateProcess terminates. It is important that CloseHandle is called after WaitForSingleObject, otherwise the call will fail since the kernel object handle is invalid.
Listing 5.3 Waits for a process to terminatevoid Listing5_3() { TCHAR szApplication[MAX_PATH]; PROCESS_INFORMATION pi; if(!GetTextResponse(_T("Enter Application to Run:"), szApplication, MAX_PATH)) return; if(CreateProcess(szApplication, NULL, NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi) == 0) cout _T("Cannot create process") endl; else { if(WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_FAILED) cout _T("Could not wait on object"); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } } Calling WaitForSingleObject is the most efficient way of waiting for a process to terminate. The call does not consume processor time while it is waiting, and does not stop the power management functions of the operating system. WaitForSingleObject is one of the synchronization functions supported by Windows CE and is described in more detail in Chapter 6.
|