服务端,即写入端
#include <iostream>
#include <string.h>
#define BUF_SIZE 1024
#ifdef _WIN32
#include <windows.h>
#define SHARENAME L"shareMemory"
HANDLE g_MapFIle;
LPVOID g_baseBuffer;
#else
#define SHARENAME "shareMemory"
#include <sys/shm.h>
#include <sys/time.h>
#include <unistd.h>
int g_shmid = -1;
char* g_baseBuffer = NULL;
#endifvoid CloseShareMemory()
{
#ifdef _WIN32if (g_baseBuffer) {FlushViewOfFile(g_baseBuffer, BUF_SIZE);UnmapViewOfFile(g_baseBuffer);g_baseBuffer = NULL;}if (g_MapFIle) {CloseHandle(g_MapFIle);g_MapFIle = NULL;}
#elseshmdt(g_baseBuffer);shmctl(g_shmid, IPC_RMID, 0);//删除
#endif
}bool CreateShareMemory()
{
#ifdef _WIN32if (g_MapFIle)CloseShareMemory();g_MapFIle = CreateFileMapping(INVALID_HANDLE_VALUE, //物理文件句柄NULL, //默认安全级别PAGE_READWRITE, //可读可写0, //高位文件大小BUF_SIZE, //地位文件大小SHARENAME //共享内存名称);if (g_MapFIle) {//映射缓存区视图,得到指向共享内存指针g_baseBuffer = MapViewOfFile(g_MapFIle, //共享内存句柄FILE_MAP_ALL_ACCESS, //可读可写许可0,0,BUF_SIZE);memset(g_baseBuffer, 0, BUF_SIZE);//初始化 置 0 return true;}
#elsekey_t key = ftok(SHARENAME, 0);g_shmid = shmget(key, BUF_SIZE, IPC_CREAT | 0666);if (g_shmid != -1) {g_baseBuffer = (char*)shmat(g_shmid, 0, 0);return true;}
#endifreturn false;
}int main()
{//创建if (!CreateShareMemory()) {std::cout << "CreateShareMemory error!\n";return -1;}//写入数据char ch[1024];while (1) {std::cout << "写入数据或输入exit退出:" << std::endl;std::cin >> ch;if (0 == strcmp(ch, "exit"))break;memcpy(g_baseBuffer, ch, 1024);}//断开 关闭CloseShareMemory();return 0;
}
客户端,即读取端
#include <iostream>
#include <string.h>
#define BUF_SIZE 1024
#ifdef _WIN32
#include <windows.h>
#define SHARENAME L"shareMemory"
HANDLE g_MapFIle;
LPVOID g_baseBuffer;
#else
#define SHARENAME "shareMemory"
#include <sys/shm.h>
#include <sys/time.h>
#include <unistd.h>
int g_shmid = -1;
char* g_baseBuffer = NULL;
#endifvoid CloseShareMemory()
{
#ifdef _WIN32if (g_baseBuffer) {FlushViewOfFile(g_baseBuffer, BUF_SIZE);UnmapViewOfFile(g_baseBuffer);g_baseBuffer = NULL;}if (g_MapFIle) {CloseHandle(g_MapFIle);g_MapFIle = NULL;}
#elseshmdt(g_baseBuffer);//shmctl(g_shmid, IPC_RMID, 0);//删除
#endif
}bool OpenShareMemory()
{
#ifdef _WIN32if (g_baseBuffer)CloseShareMemory();g_MapFIle = OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, SHARENAME);if (g_MapFIle) {g_baseBuffer = MapViewOfFile(g_MapFIle, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);return true;}
#elsekey_t key = ftok(SHARENAME, 0);g_shmid = shmget(key, BUF_SIZE, IPC_CREAT | 0666);if (g_shmid != -1) {g_baseBuffer = (char*)shmat(g_shmid, 0, 0);return true;}
#endifreturn false;
}int main()
{while (1) {//打开if (!OpenShareMemory()) {std::cout << "CreateShareMemory error!\n";return -1;}//读取char str[1024];memcpy(str, g_baseBuffer, 1024);memset(g_baseBuffer, 0, BUF_SIZE);if(str[0] != '\0')std::cout << "read value:" << str << std::endl;//断开 关闭CloseShareMemory();
#ifdef _WIN32Sleep(100);
#else#endif}return 0;
}
windows演示图
linux 演示图