Dipping into Shared Memory

来源:互联网 发布:网络综艺为什么这么火 编辑:程序博客网 时间:2024/06/08 12:10
After referring to some blogs, I gradually understand the basic usage of "Shared memory".
Basically, it contains two processes--Server and Client.
The function of the Server is as follows:
Create a physical file in hard disk.
Then create a virtual mapped file in memory and link them together.
Next initialize a pointer which points to the mapped file in memory.
Now we can manipulate the pointer to write to or read from the physical file.
#include "stdafx.h"#include "windows.h"#include "stdio.h"#include #pragma warning(disable:4996)using namespace std;int main(){//physical fileHANDLE hFile = CreateFile(TEXT("D:\\Audi\\WELCOME\\abc.txt"), GENERIC_READ | GENERIC_WRITE,0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);if (hFile == NULL){cout << "fail to create file" << endl;return 0;}//virtual mapped file in memoryHANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 1024 * 1024, TEXT("abc"));int rst = GetLastError();if (hMap == NULL && rst == ERROR_ALREADY_EXISTS){printf("hMap error\n");CloseHandle(hMap);hMap = NULL;return 0;}CHAR* pszText = NULL;//POINTERpszText = (CHAR*)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 1024 * 1024);//POINT TO mapped file in memoryif (pszText == NULL){printf("view map error!");return 0;}sprintf(pszText, "can u see me?? u r in secret spot yoho~!\n");printf(pszText);getchar();UnmapViewOfFile((LPCVOID)pszText);CloseHandle(hMap);CloseHandle(hFile);return 0;}


The function of the Client is as follows:
Open the virtual mapped file created by Server.
Then create a pointer which is similar as created by Server.
Then manipulate the pointer.

Cautious: The two processes should be running at the same time. As for me, I built two Visual Studio projects and running them at the same time.

#include "stdafx.h"#include "windows.h"#include "stdio.h"#include #pragma warning(disable:4996)using namespace std;int main(){HANDLE hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, TRUE, TEXT("abc"));if (hMap == NULL){printf("open file map error!");return 0;}CHAR* pszText = NULL;pszText = (CHAR*)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 1024 * 1024);if (pszText == NULL){printf("map view error\n");return 0;}printf(pszText);//read from memory//sprintf(pszText, "it's me again!! U are amazing!\n");//write into memorygetchar();UnmapViewOfFile(pszText);CloseHandle(hMap);hMap = NULL;return 0;}

原创粉丝点击