- 작성시간 : 2009/10/20 22:05
- 퍼머링크 : kaludin.egloos.com/2460378
- 카테고리 : 『C/C++』
출처 : Software information provider
CreateNamedPipe 사용 예제 (IPC, 명명된 파이프, 파이프, PIPE)
다음은 윈도우즈 환경에서 IPC (Inter Process Communication) 구현시에 사용할 수 있는 여러가지 방법중의 하나인
"명명된 파이프 (NamedPipe) 사용법"에 대해서 설명하고 있습니다.
먼저 파이프와 관련된 함수들을 나열하면 다음과 같습니다.
각각의 함수들에 대한 자세한 설명은 MSDN을 참고하시길 바라며,
개인적으로 중요하다 싶은 함수들은 함수옆에 별표시(★)를 달아두었습니다.
★ CreatePipe 익명 파이프 생성
★ ConnectNamedPipe 파이프 클라이언트를 기다림 (파이프 서버에서 수행하는 함수)
★ CreateNamedPipe 명명된 파이프 생성 (파이프 서버에서 수행하는 함수)
★ DisconnectNamedPipe 연결된 파이프 클라이언트의 핸들을 닫음. (파이프 서버에서 수행하는 함수)
GetNamedPipeClientComputerName
SetNamedPipeHandleState
그리고 다음은 명명된 파이프를 사용한 DayTime 예제 소스입니다. ( 가장 쉬운 예제를 생각한 끝에.. DayTime 선택 ^^;; )
예제에서 DayTime 서버의 역활은 연결된 클라이언트에 현재시간을 알려준 후, 클라이언트의 연결을 끊는 것이며,
DayTime 클라이언트의 역활은 명명된 파이프로 접근해서, 서버로 부터 읽어들인 시간을 콘솔 화면에 출력후
종료하는 기능을 수행하게 됩니다.
( ※ 예외처리가 다소 미흡하오니, 가져다 사용하실때에는 반드시 적절한 예외처리를 추가하셔야 합니다. )
1. 공통 헤더파일 선언 (서버와 클라이언트에서 공동으로 사용될 헤더파일)
#ifndef PROPERTY_H
#define PROPERTY_H#define PIPENAME "\\\\.\\Pipe\\DayTime"
#define IN_BUFF_SIZE 1024
#define OUT_BUFF_SIZE 1024
#endif /*end of PROPERTYS_H */
2. 서버 구현부 소스
#include <stdio.h>
#include <time.h>
#include <windows.h>
#include "../Property.h"
int main(int argc, char **argv)
{
int nLen = 0;
HANDLE hPipe = NULL;
BOOL bRet = FALSE;
char szTime[0xFF] = {0};
DWORD dwWrite = 0;
time_t tNow = 0;
struct tm *t = NULL; hPipe = CreateNamedPipe(
PIPENAME, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
OUT_BUFF_SIZE, // output buffer size
IN_BUFF_SIZE, // input buffer size
NMPWAIT_USE_DEFAULT_WAIT, // client time-out
NULL); // default security attribute
if ( hPipe == INVALID_HANDLE_VALUE )
{
printf("fail to CreateNamedPipe(), %d\n", GetLastError());
exit(0);
}
while (1)
{
if ( ConnectNamedPipe(hPipe, NULL) )
{
tNow = time(0);
t = localtime(&tNow);
nLen = _snprintf(szTime, 0xFF, "%02d:%02d:%02d", t->tm_hour, t->tm_min, t->tm_sec);
bRet = WriteFile(hPipe, szTime, nLen, &dwWrite, NULL);
if ( (!bRet) || (nLen != (int)dwWrite))
{
printf("fail to WriteFile, %d\n", GetLastError());
exit(0);
}
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
}
}
CloseHandle(hPipe);
return 0;
}
3. 클라이언트 구현부 소스
#include <stdio.h>
#include <windows.h>
#include "../Property.h"
int main(int argc, char* argv[])
{
HANDLE hPipe = NULL;
DWORD cbRead = 0;
char szTime[0xFF] = {0};
BOOL bRet = FALSE;
// Connect to the server pipe using CreateFile()
hPipe = CreateFile(PIPENAME, GENERIC_READ | GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
if (INVALID_HANDLE_VALUE == hPipe)
{
printf("fail to CreateFile(), %d\n", (int)GetLastError());
exit(0);
}
bRet = ReadFile(hPipe, szTime, 0xFF, &cbRead, NULL);
if ( (!bRet) || (0 == cbRead))
{
printf("fail to ReadFile(), %d\n", GetLastError());
exit(0);
}
printf("%s\n", szTime); // 서버로 부터 읽어들인 시간을 화면에 출력함.
CloseHandle(hPipe);
return 0;
}
첨부된 파일은 지금까지 설명한 DayTime 예제 소스를 압축한 파일입니다. (VS 6.0에서 작업함)



덧글
카루딘 2009/10/21 11:34 # 답글
파이프 추가 자룡http://blog.naver.com/blue7red?Redirect=Log&logNo=100042206064
카루딘 2009/10/21 18:33 # 답글
http://dhseo.egloos.com/9908479