http://blog.csdn.net/stpeace/article/details/39534361
There are many ways to communicate between processes, the last time we said the most stupid way to "share external memory/files". So, in this article, we're going to learn the "shared memory" way to communicate between processes, which is the fastest method of IPC. In some places, this "shared memory" approach is called a "memory-mapped file" approach.
Let's start by looking at process A's corresponding program:
#include <iostream> #include <windows.h>using namespace std; #define Buf_size 1025char szname[] = " Nameofmappingobject "; Shared Memory name int main () {//create shared file handle HANDLE Hmapfile = createfilemapping ( invalid_handle_value, //physical file handle NULL, //default security level Page_readwrite, //readable writable 0,// High file size buf_size, //status File size SzName //Shared memory name); Char *pbuf = (char *) mapviewoffile (hmapfile, //handle to Shared memory file_map_all_access,//read/write license 0, 0, buf_size); while (1) {cout << "input ..." << Endl; Char Szinfo[buf_size] = {0}; Gets (Szinfo); Actually gets is not safe strncpy (PBuf, Szinfo, buf_size-1);p buf[buf_size-1] = '/'; } UnmapViewOfFile (PBUF); CloseHandle (hmapfile); return 0;}
Then, let's take a look at the program that corresponds to process B:
#include <iostream> #include <windows.h>using namespace std; #define Buf_size 1025char szname[] = " Nameofmappingobject "; Shared Memory name int main () {//create shared file handle HANDLE Hmapfile = createfilemapping ( invalid_handle_value, //physical file handle NULL, //default security level Page_readwrite, //readable writable 0,// High file size buf_size, //status File size SzName //Shared memory name); Char *pbuf = (char *) mapviewoffile (hmapfile, //handle to Shared memory file_map_all_access,//read/write license 0, 0, buf_size); while (1) { cout << ' Press any button ' to receive data ... ' << Endl; GetChar (); cout << pBuf << Endl; } UnmapViewOfFile (PBUF); CloseHandle (hmapfile); return 0;}
Successively run the above two programs, get the result for ( in the word that should be than, I wrote wrong ):
Go C + + code for interprocess communication using "Shared memory" in Windows environments---leveraging createfilemapping and mapviewoffile