Windows/_System Programming
메일슬롯(MailSlot) IPC 통신 소스
Dakuo
2010. 2. 24. 00:11
/* MailRecevier */ #include <stdio.h> #include <tchar.h> #include <windows.h> #define SLOT_NAME _T("\\\\.\\mailslot\\mailbox") INT_PTR _tmain(INT_PTR argc, TCHAR *argv[]) { HANDLE hMailSlot; TCHAR messageBox[50]; ULONG_PTR bytesRead; //DWORD hMailSlot = CreateMailslot(SLOT_NAME, 0, MAILSLOT_WAIT_FOREVER, NULL); // mailslot 생성 if(hMailSlot==INVALID_HANDLE_VALUE) { _tprintf(_T("Unable to Create MailSlot!\n")); return 1; } _tprintf(_T("******** Message ********\n")); while(1) { if(!ReadFile(hMailSlot, messageBox, sizeof(TCHAR)*50, &bytesRead, NULL)) // 데이터 수신 { _tprintf(_T("Unable to Read!\n")); CloseHandle(hMailSlot); return 1; } if(!_tcsncmp(messageBox, _T("exit"), 4)) // 받은 문자열이 "exit" 일때 종료 { _tprintf(_T("Good Bye\n")); break; } messageBox[bytesRead/sizeof(TCHAR)]=0; // NULL 문자 삽입 _tprintf(_T("%s\n"), messageBox); } CloseHandle(hMailSlot); return 0; }
/* MailSender */ #include <stdio.h> #include <tchar.h> #include <windows.h> #define SLOT_NAME _T("\\\\.\\mailslot\\mailbox") INT_PTR _tmain(INT_PTR argc, TCHAR *argv[]) { HANDLE hMailSlot; TCHAR message[50]; ULONG_PTR bytesWritten; hMailSlot = CreateFile(SLOT_NAME, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hMailSlot==INVALID_HANDLE_VALUE) { _tprintf(_T("Unable to Create MailSlot!\n")); return 1; } while(1) { _tprintf(_T("My Cmd>>")); // _fputts(_T("My Cmd>>"), stdout); _tscanf(_T("%s"), message); // _fgetts(message, sizeof(message)/sizeof(TCHAR), stdin); if(!WriteFile(hMailSlot, message, _tcslen(message)*sizeof(TCHAR), &bytesWritten, NULL)) { _tprintf(_T("Unable to Write!\n")); CloseHandle(hMailSlot); } if(!_tcscmp(message, _T("exit"))) { _tprintf(_T("Good Bye!")); break; } } CloseHandle(hMailSlot); return 0; }