Win32进程间通信之共享内存

写进程

/*写进程*/
#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();
}
上一篇:SPAAC的抗体-药物偶联物(ADC)单击化学


下一篇:并发下常见的加锁及锁的PHP具体实现