//***************************************************************
// From the book "Win32 System Services: The Heart of Windows 98
// and Windows 2000"
// by Marshall Brain
// Published by Prentice Hall
//
// Copyright 1995, by Prentice Hall.
//
// This code implements a simple mailslot server (receiver) that
// blocks to efficiently wait for input, rather than polling.
// Compare with sms_recv.cpp
//***************************************************************

// sms_rec2.cpp

// Usage: sms_recv

#include <windows.h>
#include <iostream.h>

int main()
{
  char toDisptxt[80];
  HANDLE hSMS_Slot;
  DWORD nextSize;
  DWORD Msgs;
  DWORD NumBytesRead;
  BOOL Status;

  /* Create a mailslot for receiving messages */
  hSMS_Slot=CreateMailslot("\\\\.\\mailslot\\sms",
    0, 0, (LPSECURITY_ATTRIBUTES) NULL);

  /* Check and see if the mailslot was created */
  if (hSMS_Slot == INVALID_HANDLE_VALUE)
  {
    cerr << "ERROR: Unable to create mailslot" 
      << endl;
    return (1);
  }

  /* Repeatedly check for messages until the 
     program is terminated */
  while(1)
  {
    /* Block waiting for input */
    ReadFile(hSMS_Slot, toDisptxt, 0,
      &NumBytesRead, (LPOVERLAPPED) NULL))
    if (GetLastError() !=
        ERROR_INSUFFICIENT_BUFFER)
    {
      cerr << "ERROR: error during wait." 
        << endl;
      CloseHandle(hSMS_Slot);
      return (1);
    }

    Status=GetMailslotInfo(hSMS_Slot,
      (LPDWORD) NULL, &nextSize, &Msgs,
      (LPDWORD) NULL);
    if (!Status)
    {
      cerr << "ERROR: Unable to get status." 
        << endl;
      CloseHandle(hSMS_Slot);
      return (1);
    }

    /* If messages are available, then get them */
    if (Msgs)
    {

      /* Read the message and check to see if 
         read was successful */
      if (!ReadFile(hSMS_Slot, toDisptxt, nextSize,
        &NumBytesRead, (LPOVERLAPPED) NULL))
      {
        cerr 
          << "ERROR: Unable to read from mailslot" 
          << endl;
        CloseHandle(hSMS_Slot);
        return (1);
      }

      /* Display the Message */
      cout << toDisptxt << endl;
    }
    else
      /* Check for new messages twice a second */
      Sleep(500);
  } /* while */
}
