简单例子windows 共享内存 Demo -----(一)

2021-03-20 08:23

阅读:571

标签:error   进程   共享内存   span   view   def   创建线程   with   define   

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

---然后挂起6s,

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

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

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

 

 

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

#include
#include
#include
#include
#include

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

void readMemeryThread(char *str) {

}
int main()
{
  std::cout

  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     }
    else {
      std::cout     }
    Sleep(60000);
  }
  else {
    std::cout   }


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

 

 

 

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


#include
#include
#include

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

HANDLE hMap = NULL;

void readMemeryThread(char *str) {

}
int main()
{
  std::cout

  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   }
  else {
    pBuffer = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
  if (pBuffer) {
    strcpy_s((char*)pBuffer, strlen(data) + 1, data);
    std::cout    }
  else {
    std::cout     }
  }

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

 

tips:简单例子以后改良,应使用_beginthreadex创建线程。结束使用_endthreadex

简单例子windows 共享内存 Demo -----(一)

标签:error   进程   共享内存   span   view   def   创建线程   with   define   

原文地址:https://www.cnblogs.com/liuruoqian/p/12308275.html


评论


亲,登录后才可以留言!