Win32进程间通信之共享内存

47 篇文章 0 订阅
25 篇文章 1 订阅

写进程

/*写进程*/
#include <stdio.h>
#include <Windows.h>

void main()
{
	HANDLE hFileMap = CreateFileMappingA(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,1024,"ShareMemTest");
	if (hFileMap == NULL)
	{
		printf("CreateFileMapping failed.\n");
		getchar();
		return;
	}
	char* pBuf = (char*)MapViewOfFile(hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, 1024);

	if (pBuf == NULL)
	{
		printf("MapViewOfFile failed.\n");
		CloseHandle(hFileMap);
		getchar();
		return;
	}

	HANDLE hSemEmpty = CreateSemaphoreA(NULL, 1, 1, "EmptySem");
	if (hSemEmpty == NULL)
	{
		printf("Create EmptySem failed.\n");
		UnmapViewOfFile(pBuf);
		CloseHandle(hFileMap);
		getchar();
		return;
	}

	HANDLE hSemFull = CreateSemaphoreA(NULL, 0, 1, "FullSem");
	if (hSemFull == NULL)
	{
		printf("Create FullSem failed.\n");
		UnmapViewOfFile(pBuf);
		CloseHandle(hFileMap);
		CloseHandle(hSemEmpty);
		getchar();
		return;
	}

	char strMsgBuf[256] = {0};
	while (TRUE)
	{
		WaitForSingleObject(hSemEmpty, INFINITE);
		scanf("%s",strMsgBuf);
		memcpy(pBuf, strMsgBuf, strlen(strMsgBuf) + 1);
		ReleaseSemaphore(hSemFull, 1, NULL);
	}

	UnmapViewOfFile(pBuf);
	CloseHandle(hFileMap);
	CloseHandle(hSemEmpty);
	CloseHandle(hSemFull);
	getchar();
}

读进程

/*读进程*/
#include <stdio.h>
#include <Windows.h>

void main()
{
	HANDLE hFileMap = OpenFileMappingA(PAGE_READONLY, FALSE, "ShareMemTest");
	if (hFileMap==NULL)
	{
		printf("OpenFileMapping failed.\n");
		getchar();
		return;
	}
	char* pBuf = (char*)MapViewOfFile(hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, 1024);

	if (pBuf == NULL)
	{
		printf("MapViewOfFile failed.\n");
		CloseHandle(hFileMap);
		getchar();
		return;
	}

	HANDLE hSemEmpty = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, FALSE, "EmptySem");
	if (hSemEmpty == NULL)
	{
		printf("Open EmptySem failed.\n");
		UnmapViewOfFile(pBuf);
		CloseHandle(hFileMap);
		getchar();
		return;
	}

	HANDLE hSemFull = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, FALSE, "FullSem");
	if (hSemFull == NULL)
	{
		printf("Open FullSem failed.\n");
		UnmapViewOfFile(pBuf);
		CloseHandle(hFileMap);
		CloseHandle(hSemEmpty);
		getchar();
		return;
	}

	while (TRUE)
	{
		WaitForSingleObject(hSemFull, INFINITE);//请求读
		printf("%s\n",pBuf);
		ReleaseSemaphore(hSemEmpty, 1, NULL);
	}

	UnmapViewOfFile(pBuf);
	CloseHandle(hFileMap);
	CloseHandle(hSemEmpty);
	CloseHandle(hSemFull);
	getchar();
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值