Windows process Communication--shared memory (1)

Source: Internet
Author: User

The way that shared memory works is to map a physical memory to the respective virtual address space of different processes so that each process can read the same data to enable process communication. It is the most efficient method of data exchange because it is used for communication through memory operations.

The presence of Windows in a share is implemented using filemapping, which is achieved mainly through the following steps, depending on the implementation method:

1. Call CreateFileMapping to create a memory file mapping object;

 handle createfilemapping (HANDLE hfile,  //  handle to file to map   lpsecurity_ ATTRIBUTES lpfilemappingattributes,  //  optional security attributes  DWORD flprotect, //  protection for mapping object  DWORD Dwmaximumsizehigh, //  High-order-bits of object size  DWORD dwmaximumsizelow, //  Low-order-bits of object size  lpctstr lpname //  name of file-mapping object ); 

This API function creates a kernel object for a memory-mapped file that maps files to memory. Like virtual memory, a memory-mapped file can be used to preserve an area of an address space and commit the physical memory
to the region. The difference between them is that the physical memory comes from a file that is already on disk, not the system's page file.

hfile: used to identify the file handle that you want to map to the process address space. The handle can be returned by calling the C R e a T e F i l e function. Here, we do not need an actual file, so you do not need to call CreateFile to create a file, hfile This parameter can be filled in invalid_handle_value;lpfilemappingattributes : A parameter is a pointer to the SECURITY_ATTRIBUTES structure of a file-mapped kernel object, usually with a value of N U l l;flprotect: Security settings for a memory-mapped file (page_readonly Open mappings as read-only, page_readwrite open mappings in a readable, writable way, page_writecopy leave a backup for write operationsDwmaximumsizehigh: High 32 bits of the maximum length of the file map. dwmaximumsizelow: The maximum length of the file map is 32 bits lower. If both this parameter and the Dwmaximumsizehigh are zero, the actual length of the disk file is used. lpname: Specifies the name of the file mapping object, which can be used by other processes to invoke openfilemapping to open the Filemapping object.
If the creation succeeds, returns a handle to the created memory-mapped file, and returns its handle if it already exists, but the error code returned by the call to GetLastError () is: 183 (error_already_exists), or null if the creation fails;

2. Call MapViewOfFile to map to the virtual address of the current process;

If the call to CreateFileMapping succeeds, the MapViewOfFile function is called to map the memory-mapped file to the virtual address of the process;

lpvoid mapviewoffile (  HANDLE hfilemappingobject,  //  file-mapping object to map into                                // address Space  DWORD dwDesiredAccess,      //  access mode  DWORD dwfileoffsethigh,/     / high-order bits of file offset  DWORD Dwfileoffsetlow,      //  Low-order-bits of file offset  DWORD dwnumberofbytestomap< c21/>// number of bytes to map);
Hfilemappingobject:createfilemapping () returns a handle to the file image object.
dwDesiredAccess: The way to access the file data of the mapped object, and also to match the protection properties set by the CreateFileMapping () function.
Dwfileoffsethigh: Represents the high 32 bits of the file map start offset.
Dwfileoffsetlow: The low 32 bits representing the start offset of the file map.
Dwnumberofbytestomap: The number of bytes to map in the file. The 0 representation maps the entire file-map object.

3. Open the corresponding memory-mapped object in the receive process

In the data receiving process, first call the openfilemapping () function to open a named file map kernel object, get the corresponding file map kernel object handle hfilemapping; If open successfully, call MapViewOfFile () A view of the function map object that maps the file map kernel object hfilemapping to the current application's process address for read operations. (Of course, if you use CreateFileMapping, you can also get the corresponding handle)

HANDLE openfilemapping (  DWORD dwdesiredaccess,  //  access mode  BOOL bInheritHandle,    //  inherit flag  lpctstr lpname          / / pointer to name of File-mapping object);
dwDesiredAccess: dwdesiredaccess parameters of the same mapviewoffile function
bInheritHandle: This parameter is true if the handle returned by this function can be inherited by a new process initiated by the current process.
Lpname: Specifies the name of the file map object to open.

4. Read and write memory-mapped files

Once the MapViewOfFile call succeeds, it can read and write memory like the memory area of the address space of this process.

//Read operation:if(m_pviewoffile) {//read text from memory-mapped fileTCHAR S[dwmemoryfilesize]; lstrcpy (S, (LPCTSTR) m_pviewoffile);}//Write operation:if(m_pviewoffile) {TCHAR s[dwmemoryfilesize]; M_edit_box.                    GetWindowText (S, dwmemoryfilesize);                    lstrcpy ((LPTSTR) m_pviewoffile, s); //Notify All running instances the text was changed::P ostmessage (Hwnd_broadcast, Wm_message, (WPARAM) m_hwnd,0); }

5. Clean up Kernel objects

After use, the mapping of the address space of the process is canceled and the memory-mapped object is freed.

    // Cancel the mapping of the address space of   this process;     UnmapViewOfFile (PLOCALMEM);            Plocalmem=NULL;        // close File map kernel file      CloseHandle (hfilemapping);

6, simple example :

Here is a simple example to illustrate:

Example: Enter text in a process's Text dialog box, and display the previously entered content in the Text dialog box of another process.

Const 4 1024x768;  // Specify the memory-mapped file size Const LPCTSTR smemoryfilename = _t ("d9287e19-6f9e-45fa-897c-d392f73a0f2f"); // Specify the memory-mapped file name Const UINT    wm_message =     registerwindowmessage (_t ("  CC667211-7CE9-40C5-809A-1DA48E4014C4")); // Register Message

Specifying Message handler functions

Begin_message_map (Cipcdlg, CDialog)     // {{Afx_msg_map (Cipcdlg)    on_wm_syscommand ()    on_wm_paint ()    On_wm_querydragicon ()    On_ Wm_destroy ()    on_registered_message (Wm_message, onmessagetextchanged)    On_en_change (Idc_edt_text, Onchangeedttext)    //}}afx_msg_mapend_message_map ()

LRESULT cipcdlg::onmessagetextchanged (WPARAM WPARAM, LPARAM LPARAM)
{
if (WParam = = (WParam) m_hwnd)
return 0;

//Get text from memory mapped file and set it to edit box
Gettextfrommemorymappedfile ();

return 0;
}

Initialize the memory-mapped file in the window initialization function:

voidcipcdlg::initialize () {M_edit_box. Setlimittext (Dwmemoryfilesize-1); M_hfilemapping=createfilemapping (Invalid_handle_value,//System Paging FileNull//Security AttributesPage_readwrite,//Protection        0,//high-order DWORD of sizedwmemoryfilesize*sizeof(TCHAR),//low-order DWORD of sizeSmemoryfilename);//nameDWORD dwerror = GetLastError ();//if Error_already_exists//This instance isn't first (other instance created file mapping)        if( !m_hfilemapping) {MessageBox (_t ("Creating of file mapping failed")); }    Else{m_pviewoffile=MapViewOfFile (m_hfilemapping,//handle to File-mapping objectFile_map_all_access,//Desired Access            0,            0,            0);//Map all file                if( !m_pviewoffile) {MessageBox (_t ("MapViewOfFile failed")); }                //Now we have m_pviewoffile memory block which are common for//All Instances    }        if(dwerror = =error_already_exists) {        //Some Other instance is already running,//get text from existing file mappingGettextfrommemorymappedfile (); }}

Read and display the contents of the memory-mapped object:

voidCipcdlg::gettextfrommemorymappedfile () {if(m_pviewoffile) {//read text from memory-mapped fileTCHAR S[dwmemoryfilesize];                lstrcpy (S, (LPCTSTR) m_pviewoffile); //Write text to edit box. //SetWindowText raises en_change event and//Onchangeeditbox is called. Ensure that Onchangeeditbox//does setting m_bnotify to FALSEM_bnotify =FALSE; M_edit_box.                    SetWindowText (s); M_bnotify=TRUE; }}

Write the memory-mapped file in the Onchangeedttext event of the text box, and the concurrent wm_message is notified:

voidCipcdlg::onchangeedttext () {if(m_bnotify)//Change isn't done by SetWindowText    {        //write text to memory-mapped file        if(m_pviewoffile) {TCHAR s[dwmemoryfilesize]; M_edit_box.                        GetWindowText (S, dwmemoryfilesize);                        lstrcpy ((LPTSTR) m_pviewoffile, s); //Notify All running instances the text was changed::P ostmessage (Hwnd_broadcast, Wm_message, (WPARAM) M_hwnd, 0); }    }    }

At this point, one of the simplest examples of process communication through a memory-mapped file is complete, but there is a problem: the conflict between read and write is not well resolved, the memory-mapped file is a shared resource, multiple processes read and write must have synchronization problems, perhaps in this case, there is no problem, However, in the case of high frequency concurrent read and write in the actual project, how to synchronize is a problem that must be solved, not to be continued ...

Windows process Communication--shared memory (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.