Windowsで共有メモリを使う方法

Windowsで共有メモリを用いたプロセス間通信の例。今回は一方向通信。

まず送信側。

//transmiter.cpp

#include <windows.h>
#include <iostream>
#include <ctime>

using namespace std;

LPCTSTR strShareName = "JM6XXU_SHAREDMEMTEST";

void main(int argc, char** argv){
  HANDLE hShare = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
    0, 1024, strShareName);

  char *shmem, buff[1024];
  shmem = (char*)::MapViewOfFile(hShare, FILE_MAP_WRITE, 0, 0, 1024);
  time_t clock;

  for(int i=0; i<30; i++){
    clock = ::time(NULL);
    ::lstrcpy(shmem, ctime(&clock));
    cout<< shmem<< flush;
    ::Sleep(1000);
  }

  ::UnmapViewOfFile(shmem);
  ::CloseHandle(hShare);
}

次に受信側。

//reciever.cpp

#include <windows.h>
#include <iostream>
using namespace std;

LPCTSTR strShareName = "JM6XXU_SHAREDMEMTEST";

void main(int argc, char**argv){
  HANDLE hShare = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, FILE_MAP_READ,
    0, 1024, strShareName);
  if(INVALID_HANDLE_VALUE == hShare){
    cerr<<"Shared memory open failer"<< endl;
    return;
  }

  char *shmem = (char*)MapViewOfFile(hShare, FILE_MAP_READ, 0, 0, 1024);
  for(int i=0; i<30; i++){
    cout<< shmem<< flush;
    ::Sleep(1000);
  }
  ::UnmapViewOfFile(shmem);
  ::CloseHandle(hShare);
}