A simple example windows Shared Memory Demo ----- (a)

--- A process to create a shared memory, and writing data,

--- Then hang 6s,

--- Process B opens the shared memory,

--- A write data read process

--- B closed process shared memory

 

 

A process of writing data into the shared memory:

#include <iostream>
#include <windows.h>
#include <WINNT.h>
#include <tchar.h>
#include <thread>

#define SPACENAME _T("ShareMemory")
#define MEMERYDATA _T("我是数据")
#define BUF_SIZE 4096
HANDLE hMap = NULL;

void readMemeryThread(char *str) {

}
int main()
{
  std::cout << "ProcessA is ready to write the data." << std::endl;

  PszMapName = SPACENAME LPCTSTR;
  char Data [10] = "I Data";
  LPTSTR pszData = LPTSTR (Data);
  LPVOID pBuffer = NULL;

  hMap = ::CreateFileMapping(INVALID_HANDLE_VALUE,
                  NULL,
                PAGE_READWRITE,
                0,
                BUF_SIZE,
                pszMapName);
  if (hMap) {
   pBuffer = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);

    if(pBuffer) {
      strcpy_s((char*)pBuffer, strlen(data)+1, data);
      std::cout << "写入共享内存数据:" << (char*)pBuffer << std::endl;
    }
    else {
      std::cout << "wirte map error with: " << GetLastError() << std::endl;
    }
    Sleep(60000);
  }
  else {
    std::cout << "create file mapp error with: " << GetLastError() << std::endl;
  }


  if (pBuffer) {
    UnmapViewOfFile(pBuffer);
    pBuffer = NULL;
  }
  if (hMap) {
    CloseHandle(hMap);
    hMap = NULL;
  }
  system("pause");
  return 0;
}

 

 

 

Process B reads the shared data memory:


#include <windows.h>
#include <WINNT.h>
#include <tchar.h>

SPACENAME _T #define ( "ShareMemory")
#define MEMERYDATA _T ( "my data")

HANDLE hMap = NULL;

void readMemeryThread(char *str) {

}
int main()
{
  std::cout << "ProcessB is ready to read the date." << std::endl;

  PszMapName = SPACENAME LPCTSTR;
  char Data [10] = "I Data";
  LPTSTR pszData = LPTSTR (Data);
  LPVOID pBuffer = NULL;


  hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, pszMapName);

  if (hMap == NULL) {
    std::cout << "open map error with: " << GetLastError() << std::endl;
  }
  else {
    pBuffer = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
  if (pBuffer) {
    strcpy_s((char*)pBuffer, strlen(data) + 1, data);
    std::cout << "读取共享内存数据:" << (char*)pBuffer << std::endl;
   }
  else {
    std::cout << "read map error with: " << GetLastError() << std::endl;
    }
  }

  if (pBuffer) {
    UnmapViewOfFile(pBuffer);
  }
  if(hMap) {
    CloseHandle(hMap);
    hMap = NULL;
  }
  system("pause");
  return 0;
}

 

tips: simple example improved later, _beginthreadex should be used to create a thread. End use _endthreadex

Guess you like

Origin www.cnblogs.com/liuruoqian/p/12308275.html