// Creating and writing mailslot example
#include <windows.h>
#include <stdio.h>

LPTSTR SlotName = TEXT("\\\\.\\mailslot\\sample_mailslot");

BOOL WriteSlot(HANDLE hSlot, LPTSTR lpszMessage)
{
   BOOL fResult; 
   DWORD cbWritten; 
 
   fResult = WriteFile(hSlot, 
     lpszMessage, 
     (DWORD) (lstrlen(lpszMessage)+1)*sizeof(TCHAR),  
     &cbWritten, 
     (LPOVERLAPPED) NULL); 
 
   if (!fResult) 
   { 
      printf("WriteFile() failed with error code %d.\n", GetLastError()); 
      return FALSE; 
   }
   else
   {
	   printf("WriteFile() is OK!\n");
	   printf("Slot written to successfully.\n"); 
   }

   return TRUE;
}

int main(int argc, char **argv)
{ 
   HANDLE hFile; 

   hFile = CreateFile(SlotName, 
     GENERIC_WRITE, 
     FILE_SHARE_READ,
     (LPSECURITY_ATTRIBUTES) NULL, 
     OPEN_EXISTING, 
     FILE_ATTRIBUTE_NORMAL, 
     (HANDLE) NULL); 
 
   if (hFile == INVALID_HANDLE_VALUE) 
   { 
	   // GetLastError() code - http://msdn.microsoft.com/en-us/library/ms679360(VS.85).aspx
	   printf("CreateFile() failed with error code %d.\n", GetLastError());
	   return FALSE; 
   }
   else
	   printf("CreateFile() is OK!\n");
 
   WriteSlot(hFile, TEXT("Message one for mailslot."));
   WriteSlot(hFile, TEXT("Message two for mailslot."));

   Sleep(5000);

   WriteSlot(hFile, TEXT("Message three for mailslot."));
 
   if(CloseHandle(hFile) != 0)
	   printf("hFile handle was closed successfully!\n");
   else
	   printf("Fail to close hFile handle, error %d\n", GetLastError());
 
   return TRUE;
}
