WinAPI / IPC 메일슬롯 단방향 통신 예제
/*
* made by so_Sal
*/
Windows 08. IPC 프로세스간 통신
예제소스 입니다.
잘 이해가 안되는 부분이 있다면
아래 링크를 참조하세요.
LINK_
======================= Receiver =======================
#include<stdio.h>
#include<tchar.h>
#include<windows.h>
#define SLOT_NAME _T("\\\\.\\mailslot\\Mail")
int _tmain(int argc,TCHAR *argv[]){
HANDLE hMailSlot;
TCHAR messageBox[BUFSIZ];
DWORD bytesRead;
hMailSlot = CreateMailslot( //우체통 생성!!
SLOT_NAME, 0,
MAILSLOT_WAIT_FOREVER,
NULL );
if(hMailSlot == INVALID_HANDLE_VALUE){
_fputts( _T("Unable to create MailSlot ! \n"), stdout);
return 1;
}
_fputts( _T("=========== Message =========== \n"),stdout);
while(1){
if(!ReadFile(hMailSlot, messageBox, BUFSIZ, &bytesRead,NULL)){
_fputts( _T("Unable to read 1 \n"), stdout); // 글이 들어올때까지 기다리고
CloseHandle(hMailSlot); // 들어오면 읽어버림
return 1;
}
if(!_tcsncmp(messageBox, _T("EXIT"), 4)){
_fputts(_T("Good bye ! \n"), stdout);
break;
}
messageBox[bytesRead/sizeof(TCHAR)] = NULL;
_fputts(_T("Sender :: "),stdout);
_fputts(messageBox,stdout); // 읽어버린거 출력!
}
CloseHandle(hMailSlot);
return 0;
}
======================= Sender =======================
#include<stdio.h>
#include<tchar.h>
#include<windows.h>
#define SLOT_NAME _T("\\\\.\\mailslot\\Mail")
int _tmain(int argc,TCHAR *argv[]){
HANDLE hMailSlot;
TCHAR message[BUFSIZ];
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 ! \n"), stdout);
return 1;
}
while(1){
_fputts(_T("shell) "), 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(!_tcscmp(message, _T("EXIT"))){ //입력문자열이 EXIT 면 끝!
_fputts(_T("Good Bye!"), stdout);
break;
}
}
CloseHandle(hMailSlot);
return 0;
}