Synchronizing Processes

Chapter 14 also explained how threads coordinate their separate tasks by waiting for signals from synchronization objects. Besides the four standard synchronization objects—mutexes, semaphores, events, and critical sections—threads can wait for other threads and for files, timers, and processes. Waiting for a thread or a process means waiting for it to stop execution. A thread waits for a process by passing the process handle to WaitForSingleObject or WaitForMultipleObjects. When the process terminates, it enters its signaled state and all threads waiting for it resume execution.

One other synchronization command works only when waiting for processes. Instead of waiting for the process to terminate, you can wait for it to be idle. For this purpose, a process is considered idle when it has finished initializing and no user input is waiting to reach it.

DWORD WaitForInputIdle(
   HANDLE hProcess,        // process to wait for
   DWORD  dwTimeout );     // time-out time in milliseconds

Parents frequently call WaitForInputIdle immediately after creating a new process to allow the child time to establish itself. When the new process initializes and reaches its idle state, the parent can try to communicate with it.

What WaitForInputIdle returns depends on how it ends. It returns 0 for a successful wait when the process becomes idle. If the time-out period elapses before the process idles, WaitForInputIdle returns WAIT_TIMEOUT. To indicate an error, it returns (HANDLE) 0xFFFFFFFF (-1, a.k.a. INVALID_HANDLE_VALUE).

NOTE

WaitForInputIdle tests the child’s message queue for pending messages. It is intended only for GUI applications. Character-based console applications, lacking a message queue, are always idle by this definition.

© 1998 SYBEX Inc. All rights reserved.