본문 바로가기

Software/C/C++

[CBuild] File Mapping

**********************************
File Mapping을 사용하기 전에
**********************************
File Mapping은 서버와 클라이언트간에 이루어지던
아니며 일방적인 전송을 하던간에 비동기 방식으로 보내게 된다.
그러나 수신측에서는 이벤트로 받는 것이 아니라 파일을 감시하고
있어야 한다. 그러므로 수신측에서 언제 메시지가 들어왔는지 확인을
늘 하고 있어야 한다. 내가 테스트 한결과는 Timer를 이용하요,10ms까지 감시를 했지만, 특정 메시지가 빠지는 경우가 있었다. 즉, 수신하지 못하는 경우가 있었다. 그러므로 이를 빠지지 않고 받기위해서는 다른 검사 방법을 강구해야 한다. 확인 해 볼수 있는것이 thread나 callback함수등을 이용하여 테스트를 해볼필요는 있다.
/////////////Server//////////////
#include <windows.h>

HANDLE hFile, hMapFile;

hFile = CreateFile(  lpszName,              // name of existing file
        GENERIC_READ | GENERIC_WRITE,  // read/write access
        0,                                    // no sharing
        NULL,                                  // default security
        OPEN_ALWAYS,                        // open existing or new
        FILE_ATTRIBUTE_NORMAL,              // file attributes
        NULL);                                // no template

if (hFile == INVALID_HANDLE_VALUE )
{
  ErrorHandler("Could not open file.");
}

hMapFile = CreateFileMapping( hFile,      // current file handle
          NULL,                              // default security
          PAGE_READWRITE,  // read/write permission
          0,                                  // max. object size
          0,                                  // size of hFile
          "MyFileMappingObject");            // name of mapping object

if (hMapFile == NULL)
{
    ErrorHandler("Could not create file mapping object.");
}
LPVOID lpMapAddress;
lpMapAddress = MapViewOfFile(  hMapFile, // handle to mapping object
            FILE_MAP_ALL_ACCESS,              // read/write permission
            0,                                // max. object size
            0,                                // size of hFile
            0);                                // map entire file

if (lpMapAddress == NULL)
{
  ErrorHandler("Could not map view of file.");
}

///////////Client/////////////
HANDLE hMapFile;
LPVOID lpMapAddress;

hMapFile = OpenFileMapping( FILE_MAP_ALL_ACCESS, // read/write permission
          FALSE,                            // Do not inherit the name
          "MyFileMappingObject");            // of the mapping object.

if (hMapFile == NULL)
{
    ErrorHandler("Could not open file mapping object.");
}

lpMapAddress = MapViewOfFile( hMapFile, // handle to mapping object
          FILE_MAP_ALL_ACCESS,              // read/write permission
          0,                                // max. object size
          0,                                // size of hFile
          0);                                // map entire file
 
if (lpMapAddress == NULL)
{
  ErrorHandler("Could not map view of file.");
}

//////////////To Read//////////////
DWORD dwLength;

dwLength = *((LPDWORD) lpMapAddress);
/////////////To Write///////////////
*((LPDWORD) lpMapAddress) = dwLength;