码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2020-02-14 18:37:11      阅读:80      评论:0      收藏:0      [点我收藏+]

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

---进程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 -----(一)

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!