memoryShare_WriteServer:
```
// ConApp1Memoryshare1Readserver181101.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <string>
#pragma warning(disable:4996)
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//
{//内存写入数据代码块-
char *endstr = "end";
string strMapName("ShareMemory");// 内存映射对象名称
string strData;//用于存储写入数据
string strNULL = "";
string strS1 = "s";
LPVOID pBuffer;// 共享内存指针
HANDLE hMap;//定义一个句柄
pBuffer = "12";
cout << "在下面(用键盘)输入变量(char *)pBuffer的值,如:" << (char *)pBuffer << endl;
do {
getline(cin, strData);//读取一行数据给strData
hMap = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, strData.size(), (LPCWSTR)strMapName.c_str());
pBuffer = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);//得到与共享内存映射的指针
if (strS1!=strData && strNULL != strData) {
strcpy((char*)pBuffer, strData.c_str());//写入数据
cout << "写入共享内存数0据:" << (char *)pBuffer << endl;
//持续检测数据内容
if (!strcmp("end", (char*)pBuffer)) { cout << "[" << (char*)pBuffer << "]"; }
}
if (strS1 == strData) { cout << "[s:" << (char*)pBuffer << endl; }
//if ((strNULL==strData)) { cout << "写入共享内存数3据:" << (char *)pBuffer << endl; }
//
} while (strcmp("end", (char*)pBuffer));
system("pause");
::UnmapViewOfFile(pBuffer);//停止指针到共享内存的映射
::CloseHandle(hMap);//关闭共享内存的句柄 return 0;
//-------------------- -
}//内存写入数据代码块-End
return 0;
}//int _tmain(int argc, _TCHAR* argv[])
```
memoryshare_ReadClient181001
```
// Cons1Memoryshare02Client181104.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//
{
string strMapName("ShareMemory");// 内存映射对象名称
string strData;//用于存储共享内存中的数据
LPVOID pBuffer=NULL;// 共享内存指针
HANDLE hMap;
char * cha_ptr;
do {//do100
hMap = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, (LPCWSTR)strMapName.c_str());// 先判断要打开的共享内存名称是否存在
if (NULL == hMap) { cout << "尚未创建共享内存" << endl; }//if110
else {//if110else110
//共享内存存在,获得指向共享内存的指针,显示出数据
pBuffer = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
cha_ptr = (char *)pBuffer;
// cout << "读取出共享内存数0据:" << (char *)pBuffer << endl;
if ('0' != cha_ptr[0]) {//if220
cout << "读取出共享内存数据b:" << (char *)pBuffer << endl;
//更改标志位为2(已读)
cha_ptr[0] = '0';
}//if220
//
//
}//if110else110
Sleep(1000);
} while (true); //do100while110
system("pause");
::UnmapViewOfFile(pBuffer);
::CloseHandle(hMap);
//-------------------- -
}
return 0;
}//int _tmain(
```