简单例子windows 共享内存 Demo -----

Posted liuruoqian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单例子windows 共享内存 Demo -----相关的知识,希望对你有一定的参考价值。

---进程A创建共享内存,并且写入数据,

---然后挂起6s,

---进程B打开共享内存,

---读取进程A写入的数据

---进程B关闭共享内存

 

 

进程A写数据进入共享内存:

#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;

  LPCTSTR pszMapName = SPACENAME;
  char data[10] = "我是数据";
  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;
}

 

 

 

进程B读取共享内存中数据:


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

#define SPACENAME _T("ShareMemory")
#define MEMERYDATA _T("我是数据")

HANDLE hMap = NULL;

void readMemeryThread(char *str) {

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

  LPCTSTR pszMapName = SPACENAME;
  char data[10] = "我是数据";
  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:简单例子以后改良,应使用_beginthreadex创建线程。结束使用_endthreadex

以上是关于简单例子windows 共享内存 Demo -----的主要内容,如果未能解决你的问题,请参考以下文章

2017-2018-1 20155317 IPC

Flink Java Demo(Windows)

C共享内存双向量

深入详解Linux进程间通信之共享内存(Shared Memory)

深入详解Linux进程间通信之共享内存(Shared Memory)

深入详解Linux进程间通信之共享内存(Shared Memory)