windows进程通信共享内存客户端服务端源代码
时间: 2023-07-20 12:15:52 浏览: 58
以下是一个使用共享内存进行进程间通信的客户端和服务端的示例代码,代码中包括了创建和映射共享内存,以及读写共享内存的基本操作。
服务端代码:
```
#include <windows.h>
#include <stdio.h>
int main()
{
HANDLE hMapFile;
LPCTSTR pBuf;
// 创建共享内存
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // 使用无效的句柄
NULL, // 默认安全级别
PAGE_READWRITE, // 可读写
0, // 高位字节数
1024, // 低位字节数
TEXT("MyFileMappingObject")); // 共享内存名称
if (hMapFile == NULL)
{
printf("CreateFileMapping failed (%d)\n", GetLastError());
return 1;
}
// 映射共享内存
pBuf = (LPTSTR)MapViewOfFile(
hMapFile, // 共享内存句柄
FILE_MAP_ALL_ACCESS,// 可读写
0,
0,
1024);
if (pBuf == NULL)
{
printf("MapViewOfFile failed (%d)\n", GetLastError());
CloseHandle(hMapFile);
return 1;
}
// 从共享内存中读取数据
printf("Buf: %s\n", pBuf);
// 写入数据到共享内存
CopyMemory((LPVOID)pBuf, "Hello from server!", sizeof("Hello from server!"));
// 解除映射
UnmapViewOfFile(pBuf);
// 关闭句柄
CloseHandle(hMapFile);
return 0;
}
```
客户端代码:
```
#include <windows.h>
#include <stdio.h>
int main()
{
HANDLE hMapFile;
LPCTSTR pBuf;
// 打开共享内存
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // 可读写
FALSE, // 不继承
TEXT("MyFileMappingObject")); // 共享内存名称
if (hMapFile == NULL)
{
printf("OpenFileMapping failed (%d)\n", GetLastError());
return 1;
}
// 映射共享内存
pBuf = (LPTSTR)MapViewOfFile(
hMapFile, // 共享内存句柄
FILE_MAP_ALL_ACCESS,// 可读写
0,
0,
1024);
if (pBuf == NULL)
{
printf("MapViewOfFile failed (%d)\n", GetLastError());
CloseHandle(hMapFile);
return 1;
}
// 写入数据到共享内存
CopyMemory((LPVOID)pBuf, "Hello from client!", sizeof("Hello from client!"));
// 从共享内存中读取数据
printf("Buf: %s\n", pBuf);
// 解除映射
UnmapViewOfFile(pBuf);
// 关闭句柄
CloseHandle(hMapFile);
return 0;
}
```
此代码演示了如何创建一个共享内存对象,并分别在服务端和客户端中映射到进程地址空间中,然后进行数据读写。在实际应用中,需要根据具体需求进行修改和扩展。