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(
```