Vienna
Chapter 7) 프로세스 간 통신(IPC) 1 - 메일슬롯 방식의 IPC 본문
■ 메일 슬롯 방식의 IPC
◇ Receiver 측의 준비
HANDLE CreateMailSlot(
LPCTSTR lpName, // 1
DWORD nMaxMessageSize, // 2
DWORD lReadTimeout, // 3
LPSECURITY_ATTRIBUTES lpSecurityAttirbutes // 4
);
lpName | 생성하는 메일슬롯의 이름을 결정 == 주소를 지정 |
nMaxMessageSize | 메일슬롯의 버퍼 크기를 지정 |
lReadTimeout | 메일 슬롯이 비어있을 경우 얼마나 오래 Blocking 상태에 놓일 것인가? |
lpSecurityAttirbutes | 핸들을 상속하기 위한 용도로 사용 |
◇ Sender 측의 준비
// 1단계
HANDLE hMailSlot;
hMailSlot = CreateFile("\\\.\\mailslot\\mailbox", ...);
// 2단계
CHAR message[50];
WriteFile(hMailSlot, message, ...);
■ 메일 슬롯의 예
/*
* MailReceiver.cpp
*
* 프로그램 설명: 메일슬롯 Receiver
*/
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#define SLOT_NAME _T("\\\\.\\mailslot\\mailbox")
int _tmain(int argc, TCHAR * argv[])
{
HANDLE hMailSlot;
TCHAR messageBox[50];
DWORD bytesRead;
// mailSlot 생성
hMailSlot = CreateMailslot(SLOT_NAME, 0, MAILSLOT_WAIT_FOREVER, NULL);
if (hMailSlot == INVALID_HANDLE_VALUE) {
_fputts(_T("Unable to create mailslot"), stdout);
return 1;
}
// Message 수신
_fputts(_T("******** Message ********"), stdout);
while (1) {
if (!ReadFile(hMailSlot, messageBox, sizeof(TCHAR) * 500, &bytesRead, NULL)) {
CloseHandle(hMailSlot);
return 1;
}
if (!_tcsncmp(messageBox, _T("exit"), 4)) {
_fputts(_T("Good bye!"), stdout);
break;
}
messageBox[bytesRead / sizeof(TCHAR)] = 0;
_fputts(messageBox, stdout);
}
CloseHandle(hMailSlot);
return 0;
}
/*
* MailSender.cpp
*
* 프로그램 설명: 메일슬롯 Sender
*/
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#define SLOT_NAME _T("\\\\.\\mailslot\\mailbox")
int _tmain(int argc, TCHAR* argv[])
{
HANDLE hMailSlot;
TCHAR message[50];
DWORD bytesWritten;
hMailSlot = CreateFile(SLOT_NAME, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hMailSlot == INVALID_HANDLE_VALUE) {
_fputts(_T("Unable to create mailslot"), stdout);
return 1;
}
while (1) {
_fputts(_T("MY CMD>"), stdout);
_fgetts(message, sizeof(message)/sizeof(TCHAR), stdin);
if (!WriteFile(hMailSlot, message, _tcslen(message) * sizeof(TCHAR), &bytesWritten, NULL)) {
_fputts(_T("Unable to write!"), stdout);
CloseHandle(hMailSlot);
return 1;
}
if (!_tcsncmp(message, _T("exit"), 4)) {
_fputts(_T("Good bye!"), stdout);
break;
}
}
CloseHandle(hMailSlot);
return 0;
}
◇ 메일슬롯 IPC의 고찰
메일슬롯은 한쪽 방향으로만 메시지를 전달할 수 있다.
따라서 두 프로세스가 서로 메시지를 주고 받을 수 있는 채팅 프로그램 구현을 위해서는 두 개의 메일슬롯을 생성해야만 한다.
또, 메일슬롯은 브로드캐스팅(Broeadcasting) 방식의 통신을 지원한다.
'그외 > 뇌를 자극하는 윈도우즈 시스템 프로그래밍' 카테고리의 다른 글
Chapter 8) 프로세스 간 통신(IPC) 2 - 핸들 테이블과 오브젝트 핸들의 상속 (1) (0) | 2023.04.21 |
---|---|
Chapter 7) 프로세스 간 통신(IPC) 1 - Signaled vs Non-Signaled (0) | 2023.04.20 |
Chapter 7) 프로세스 간 통신(IPC) 1 - IPC의 의미 (0) | 2023.04.18 |
Chapter 18) 파일 I/O와 디렉터리 컨트롤 - 파일 열기/닫기/읽기/쓰기 (0) | 2023.04.17 |
Chapter 6) 커널 오브젝트와 오브젝트 핸들 - 커널 오브젝트에 대한 이해 (0) | 2023.04.16 |
Comments