15.2.3 Reading From a Mailslot

The process that creates a mailslot can read messages from it, using the mailslot handle in a call to the ReadFile function. The following code fragment calls the GetMailslotInfo function to determine whether there are any messages in the mailslot. If there are waiting messages, each message is displayed in a message box, along with information about how many messages remain to be read.

BOOL FAR PASCAL Readslot(HWND hwnd, HDC hdc)

{

DWORD cbMessage, cMessage, cbRead;

BOOL fResult;

LPSTR lpszBuffer;

CHAR achID[80];

DWORD i;

cbMessage = cMessage = cbRead = 0;

fResult = GetMailslotInfo(hSlot1, /* mailslot handle */

(LPDWORD) NULL, /* no maximum message size */

&cbMessage, /* size of next message */

&cMessage, /* number of messages */

(LPDWORD) NULL); /* read timeout */

if(!fResult) {

ErrorHandler(hwnd, "GetMailslotInfo");

return FALSE;

}

if(cMessage == 0)

TextOut(hdc, 10, 10, "No waiting messages.", 20);

else { /* retrieve each message */

for (i = 0; i < cMessage; i++) {

/* Build string identifying message number. */

wsprintf((LPSTR) achID,

"\nMessage #%d of %d\n", i + 1, cMessage);

/* Allocate memory for message. */

lpszBuffer = (LPSTR) GlobalAlloc(GPTR,

lstrlen((LPSTR) achID) + cbMessage);

lpszBuffer[0] = '\0';

fResult = ReadFile(hSlot1,

lpszBuffer,

cbMessage,

&cbRead,

(LPOVERLAPPED) NULL);

if(!fResult) {

ErrorHandler(hwnd, "ReadFile");

GlobalFree((HGLOBAL) lpszBuffer);

return FALSE;

}

/* Concatenate message and message-number string. */

lstrcat(lpszBuffer, (LPSTR) achID);

MessageBox(hwnd,

lpszBuffer,

"Contents of Mailslot",

MB_OK);

GlobalFree((HGLOBAL) lpszBuffer);

}

}

return TRUE;

}

A mailslot exists until the CloseHandle function has been called for all open server handles or until all server processes that own a mailslot handle have exited. In either case, any unread messages are deleted from the mailslot, all client handles to the mailslot are closed, and the mailslot itself is deleted from memory.