服务端,即写入端
#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;
#endif
void CloseShareMemory()
{
#ifdef _WIN32
if (g_baseBuffer) {
FlushViewOfFile(g_baseBuffer, BUF_SIZE);
UnmapViewOfFile(g_baseBuffer);
g_baseBuffer = NULL;
}
if (g_MapFIle) {
CloseHandle(g_MapFIle);
g_MapFIle = NULL;
}
#else
shmdt(g_baseBuffer);
shmctl(g_shmid, IPC_RMID, 0);//删除
#endif
}
bool CreateShareMemory()
{
#ifdef _WIN32
if (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;
}
#else
key_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;
}
#endif
return 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;
#endif
void CloseShareMemory()
{
#ifdef _WIN32
if (g_baseBuffer) {
FlushViewOfFile(g_baseBuffer, BUF_SIZE);
UnmapViewOfFile(g_baseBuffer);
g_baseBuffer = NULL;
}
if (g_MapFIle) {
CloseHandle(g_MapFIle);
g_MapFIle = NULL;
}
#else
shmdt(g_baseBuffer);
//shmctl(g_shmid, IPC_RMID, 0);//删除
#endif
}
bool OpenShareMemory()
{
#ifdef _WIN32
if (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;
}
#else
key_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;
}
#endif
return 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 _WIN32
Sleep(100);
#else
#endif
}
return 0;
}
windows演示图
linux 演示图