Named shared memory for Windows interprocess communication

Keywords: C++ Windows MFC

summary

   named shared memory mainly uses several API functions provided by windows to create, open, read and destroy named shared memory. Shared memory is more suitable for scenarios with message servers and message consumers. Its advantages are high efficiency and suitable for sharing more information. Its disadvantages are that it is not suitable for scenarios where both parties need to communicate information frequently.
  the following procedures are divided into two parts: one is the message service process responsible for producing messages, and the other is the message consumption process responsible for consuming messages; The former creates a named shared memory with the specified name and writes the service message to the shared memory, while the latter opens the named shared memory with the specified name and reads and prints the message
The main content of this article comes from Microsoft official documents: Create named shared memory

Message server

Working process of server program

  the service process uses the CreateFileMapping interface to create named shared memory. To write data to the named shared memory, you need to call the mapviewofile interface, and the mapviewofile function returns a pointer pBuf pointing to the shared memory. Finally, the process uses the CopyMemory function to write a string data to shared memory.
Just look at Microsoft's example code:

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>

#define BUF_SIZE 256 / / describes the shared memory size
TCHAR szName[]=TEXT("Global\\MyFileMappingObject"); // Global ID all processes started by windows users can access this memory to each other. Administrator permission is required. If this requirement is not met, the global ID can be omitted
TCHAR szMsg[]=TEXT("Message from first process."); // data

int _tmain()
{
   HANDLE hMapFile;
   LPCTSTR pBuf;

   hMapFile = CreateFileMapping(
                 INVALID_HANDLE_VALUE,    // use paging file
                 NULL,                    // default security
                 PAGE_READWRITE,          // read/write access
                 0,                       // maximum object size (high-order DWORD)
                 BUF_SIZE,                // maximum object size (low-order DWORD)
                 szName);                 // name of mapping object

   if (hMapFile == NULL)
   {
      _tprintf(TEXT("Could not create file mapping object (%d).\n"),
             GetLastError());
      return 1;
   }
   pBuf = (LPTSTR) MapViewOfFile(hMapFile,   // handle to map object
                        FILE_MAP_ALL_ACCESS, // read/write permission
                        0,
                        0,
                        BUF_SIZE);

   if (pBuf == NULL)
   {
      _tprintf(TEXT("Could not map view of file (%d).\n"),
             GetLastError());

       CloseHandle(hMapFile);

      return 1;
   }


   CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
    _getch();

   UnmapViewOfFile(pBuf);

   CloseHandle(hMapFile);

   return 0;
}

Message end

Working process of consumer program

   the consumer process returns a memory mapped handle by calling the OpenFileMapping function, which specifies the name selected when the service process is created. Use this handle to obtain a pointer to the shared memory by calling MapViewOfFile, and the data in the shared memory can be read from the array
The specific codes are as follows:

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")

#define BUF_SIZE 256
TCHAR szName[]=TEXT("Global\\MyFileMappingObject");

int _tmain()
{
   HANDLE hMapFile;
   LPCTSTR pBuf;

   hMapFile = OpenFileMapping(
                   FILE_MAP_ALL_ACCESS,   // read/write access
                   FALSE,                 // do not inherit the name
                   szName);               // name of mapping object

   if (hMapFile == NULL)
   {
      _tprintf(TEXT("Could not open file mapping object (%d).\n"),
             GetLastError());
      return 1;
   }

   pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
               FILE_MAP_ALL_ACCESS,  // read/write permission
               0,
               0,
               BUF_SIZE);

   if (pBuf == NULL)
   {
      _tprintf(TEXT("Could not map view of file (%d).\n"),
             GetLastError());

      CloseHandle(hMapFile);

      return 1;
   }

   MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);

   UnmapViewOfFile(pBuf);

   CloseHandle(hMapFile);

   return 0;
}

Posted by taldos on Wed, 03 Nov 2021 02:00:00 -0700