开发环境:window 10 Qt5.13.1
windows下的进程间通信有多种方式,管道,无名管道,共享内存,消息,Socket等,但不的方式使用的场景不同,如现在有一个场景是,程序A(C++语言)调用程序B(C语言)时时获取程序B的进度,如果用管道读取一个进度就退出了,使用起来不方便,而共享内存可以时时读取放在共享内存上的进度时,操作起来也比较方便,使用的API有三个,如下:
CreateFileMapping()//创建共享内存
MapViewOfFile()//将共享内存映射到进程的地址空间
OpenFileMapping()//打开共享内存
代码示例如下:
服务端,读取数据:
#include <stdio.h>
#include <Windows.h>
int createSharedMemory()
{
TCHAR szName[] = TEXT("Global\\Position");
LPVOID pBuffer;//共享内存指针
//1.创建共享内存
HANDLE hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, BUF_SIZE, szName);
if(NULL == hMapFile)
{
qDebug() << "Create file mapping object failed=======" << GetLastError();
return -1;
}
//2.获取与共享内存映射的指针
pBuffer = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
//3.循环读取数据
int index = 0;
while(1)
{
qDebug() << "read data ======" << QString((char *)pBuffer) << ++index;
Sleep(1000);
}
UnmapViewOfFile(pBuffer);
CloseHandle(hMapFile);
hMapFile = NULL;
return 0;
}
int main()
{
int aa = createSharedMemory();
printf("Hello World! aa ===============%d\n", aa);
return 0;
}
客户端,写数据:
#include <stdio.h>
#include <Windows.h>
int createSharedMemory()
{
TCHAR szName[] = TEXT("Global\\Position");
LPVOID pBuffer;//共享内存指针
//1.打开共享内存
HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, szName);
if(NULL == hMapFile)
{
printf("open file mapping object failed=======%d\n", GetLastError());
return -1;
}
//2.获取与共享内存映射的指针
pBuffer = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
//3.循环读取数据
int a = 0;
while(1)
{
char szName[16];
sprintf(szName, "sharemap=%d", ++a);
strncpy(pBuffer, szName, strlen(szName));
printf("write data ======%s\n", (char *)pBuffer);
Sleep(1000);
}
UnmapViewOfFile(pBuffer);
CloseHandle(hMapFile);
hMapFile = NULL;
return 0;
}
int main()
{
int aa = createSharedMemory();
printf("Hello World! aa ===============%d\n", aa);
return 0;
}
服务端也可以写数据,客户端也可以读数据,修改一些代码即可实现
参考文档:
https://docs.microsoft.com/en-us/windows/win32/memory/creating-named-shared-memory
https://blog.youkuaiyun.com/stpeace/article/details/39534361
https://blog.youkuaiyun.com/u013052326/article/details/76359588
https://www.cnblogs.com/dongsheng/p/4460944.html
update:2020-03-28