目录
创建共享内存
读/写其他进程创建出来的共享内存
创建共享内存
#include <Windows.h>
#include <stdio.h>
struct Test
{
char name[100];
int age;
}test;
HANDLE hMutex;
int main()
{
if ((hMutex=OpenMutex(MUTEX_ALL_ACCESS, false, "MyMutex")) == nullptr)
{
hMutex = CreateMutex(0, false, "MyMutex");
}
strcpy(test.name,"zhagnsan");
test.age = 18;
SECURITY_ATTRIBUTES sa;
sa.bInheritHandle = true;
sa.lpSecurityDescriptor = NULL;
sa.nLength = sizeof(sa);
//创建共享内存句柄
//如果hFile是INVALID_HANDLE_VALUE ,调用进程还必须在dwMaximumSizeHigh和 dwMaximumSizeLow参数中指定文件映射对象的大小。在这种情况下, CreateFileMapping创建一个指定大小的文件映射对象,该对象由系统分页文件支持,而不是由文件系统中的文件支持。
//为指定文件创建或打开命名或未命名文件映射对象
HANDLE hFileHandle = CreateFileMapping(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, 0, sizeof(Test), "MyFile");
printf("hFileHandle=%d\n",hFileHandle);
//在调用进程的地址空间映射一个文件视图
char* sharedMemory = (char*)MapViewOfFile(hFileHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0);
//使用互斥对象保证同一时刻只允许一个进程读或写共享内存
WaitForSingleObject(hMutex, INFINITE);
memcpy(sharedMemory, &test, sizeof(Test));
ReleaseMutex(hMutex);
UnmapViewOfFile(sharedMemory); //从调用进程的地址空间取消映射文件的映射视图
//直接将文件映射对象句柄传给其他进程
//char cmd[1024];
//sprintf(cmd, "%i", hFileHandle);
//STARTUPINFOA startupInfo = {0};
//startupInfo.cb = sizeof(startupInfo);
//PROCESS_INFORMATION processInfo = {0};
//delete count;
//count = nullptr;
//if (!CreateProcess("D:\\MyCode\\win32\\共享内存\\Debug\\共享内存2.exe", cmd, 0, 0, true, CREATE_NEW_CONSOLE, 0, 0, &startupInfo, &processInfo))
//{
// printf("CreateProcess failed\n");
//}
//else
//{
// printf("CreateProcess sucessed\n");
//}
//CloseHandle(hFileHandle);
getchar();
return 0;
}
读/写其他进程创建出来的共享内存
#include <Windows.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
struct Test
{
char name[100];
int age;
}test;
HANDLE hMutex;
int main(int argc,char** argv)
{
if ((hMutex=OpenMutex(MUTEX_ALL_ACCESS, false, "MyMutex")) == nullptr)
{
hMutex = CreateMutex(0, false, "MyMutex");
}
//HANDLE hFileHandle = (HANDLE)(atol(argv[0]));
HANDLE hFileHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, true, "MyFile");
printf("fileHandle=%d\n",hFileHandle);
char* sharedMemory = (char*)MapViewOfFile(hFileHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0);
WaitForSingleObject(hMutex, INFINITE);
ofstream fileStream("C:\\Users\\Administrator\\Desktop\\test.txt", ios_base::app);
for (int i = 0; i < 10; i++)
{
memcpy(&test, sharedMemory, sizeof(test));
//printf("name=%s\nage=%d\n", test.name, test.age);
fileStream << GetCurrentProcessId()<<"\t"<<GetCurrentThreadId()<<"\t"
<<test.age
<< endl<<flush;
//修改共享内存数据
test.age += 1;
memcpy(sharedMemory, &test, sizeof(test));
Sleep(100);
}
fileStream << "----------------------------------\n";
fileStream.close();
ReleaseMutex(hMutex);
//getchar();
return 0;
}
|