The sharing of data between processes: shared memory
The sharing of data between processes can be used to achieve shared memory, in Win32, the process between the use of shared memory is mapped file. Virtual memory system is mapped to the actual memory pages or the ability to exchange files. Users can be mapped to any memory mapping files, including system memory page. The use of system memory page can be achieved fast shared memory.
Utilization of shared memory between the process of achieving a total of two data sharing:
1. CreateFileMapping function used to create memory-mapped file. This function need to handle paper, the shared memory for most applications, built this file handle xFFFFFFFF can be set to 0. Handle this point system memory pages of documents.
2. Mapping document creating successful after its return to the handle as a parameter, call MapViewOfFile memory mapping function for creating documents as objects, MapViewOfFile function will return as indicators point to the document. This can be used as means for memory-mapped files operation, the read-write memory to simplify the operation as ordinary variables.
Below is a process to achieve the utilization of shared memory between the Sample data sharing procedures.
/ / Write memory process
/ / MemWrite.cpp
# Include "stdafx.h"
# Include "windows.h"
# Include "iostream.h"
Class student
(
Public:
Long ID;
Char name [20];
);
Void main ()
(
HANDLE hMemShare;
Student stu;
Int stu_num = 30;
* Lpstu student;
Stu.ID = 99041232;
Strcpy (stu.name, "SecBug");
CreateFileMapping hMemShare = ((HANDLE) 0xFFFFFFFF, NULL, PAGE_READWRITE, 0, sizeof (student), "TestMemShare");
If (hMemShare == NULL)
(
Cout << "Failed to Alloocate" <<endl;
Return;
)
Lpstu = (student *) MapViewOfFile (hMemShare, FILE_MAP_WRITE, 0, 0, sizeof (student));
If (lpstu == NULL)
(
Cout << "Failed to Map" <<endl;
Return;
)
* Lpstu = stu;
While (1) ()
UnmapViewOfFile (lpstu);
)
/ / Read memory process
/ / MemRead.cpp
# Include "stdafx.h"
# Include "windows.h"
# Include "iostream.h"
Class student
(
Public:
Long ID;
Char name [20];
);
Void main ()
(
HANDLE hMemShare;
Student stu;
* Lpstu student;
Char * lpTch;
Stu.ID = 0;
Strcpy (stu.name, "tst");
HMemShare = OpenFileMapping (FILE_MAP_READ, FALSE, "TestMemShare");
If (hMemShare == NULL)
(
Cout << "File Created Failed" <<endl;
Return;
)
Lpstu = (student *) MapViewOfFile (hMemShare, FILE_MAP_READ, 0, 0, sizeof (student));
If (lpTch == NULL)
(
Cout << "Failed to Map" <<endl;
Return;
)
Lpstu stu = *;
Cout <<stu.ID <<endl;
Cout <<stu.name <<endl;
UnmapViewOfFile (lpstu);
)
Tags: memory








0 Comments to “The sharing of data between processes: shared memory”
No Comments. Send your comment.
Leave a Reply
You must be logged in to post a comment.