Listing 9: Routine that blocks for an I/O request

nmpipe_eRetcode nmpipe_cNamedPipe::BlockForIO(HANDLE hUserEvent,
    DWORD TimeOut, DWORD cbExpected)
{
    HANDLE hEvents[2];
    int    NumEvents = 0;

    hEvents[NumEvents++] = Overlap.hEvent;

    if (hUserEvent) {
        hEvents[NumEvents++] = hUserEvent;
    }

    DWORD rc = WaitForMultipleObjects(NumEvents, hEvents,
        FALSE,    // Wait for pipe operation or "user" event.
        TimeOut);

    if (rc == WAIT_FAILED) {
        REPORT("Failure: WaitForMultipleObjects() -- WinError = %u\n",
            GetLastError());
        return nmpipeError;
    }

    if (rc == WAIT_TIMEOUT) {
        REPORT("Failure: WaitForMultipleObjects() -- time-out\n");
        return nmpipeTimeOut;
    }

    DWORD ihEvents = rc - WAIT_OBJECT_0;

    if (hUserEvent && (hEvents[ihEvents] == hUserEvent)) {
        REPORT("User event received.\n");
        return nmpipeEvent;
    }

    if (hEvents[ihEvents] == Overlap.hEvent) {
        return GetAvailableData(cbExpected);
    }

    REPORT("Failure: WaitForMultipleObjects() -- WinError = %u\n",
            GetLastError());

    return nmpipeError;
}
//End of File