Mailslot에 쓰기

mailslot에 쓰는 것은 표준 디스크 파일에 쓰는 것과 비슷합니다. 다음 코드에서는 CreateFile, WriteFileCloseHandle 함수를 사용하여 짧은 메시지를 mailslot에 넣습니다. 메시지는 로컬 컴퓨터의 "sample_mailslot"라는 mailslot 서버로 브로드캐스트됩니다. 이 코드는 mailslot 서버가 이미 만들어졌다는 가정 하에 작동합니다.

#include <windows.h>
#include <stdio.h>

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

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

   return TRUE;
}

int main()
{ 
   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) 
   { 
      printf("CreateFile failed with %d.\n", GetLastError()); 
      return FALSE; 
   } 
 
   WriteSlot(hFile, TEXT("Message one for mailslot."));
   WriteSlot(hFile, TEXT("Message two for mailslot."));

   Sleep(5000);

   WriteSlot(hFile, TEXT("Message three for mailslot."));
 
   CloseHandle(hFile); 
 
   return TRUE;
}

다음은 Mailslot에서 읽기에 표시된 mailslot 서버와 함께 이 예제를 실행할 때 표시되는 출력입니다.

Slot written to successfully.
Slot written to successfully.
Slot written to successfully.