基于C++的进程间共享内存通信

1、Writer端

  参照上篇共享内存通信创建过程,内存写入端代码如下所示,其中写入端与读取端的共享内存名称、互斥量名称要保持唯一一致

 1 // 共享内存数据结构,并保持单字节对齐
 2 #pragma pack(push, 1) 
 3 struct SharedData {
 4     int count;
 5     char buffer[256];
 6 };
 7 #pragma pack(pop)
 8 
 9 int main()
10 {
11     int a = sizeof(SharedData);
12     std::cout << "the value of a is:" << a << std::endl;
13     // 创建或打开共享内存
14     HANDLE hMapFile = CreateFileMapping(
15         INVALID_HANDLE_VALUE,   // 使用物理内存而非文件
16         NULL,                   // 默认安全属性
17         PAGE_READWRITE,         // 可读可写
18         0,                      // 内存大小高位
19         sizeof(SharedData),     // 内存大小低位
20         L"MySharedMemory"       // 共享内存名称(需唯一)
21     );
22 
23     if (hMapFile == NULL) {
24         std::cerr << "CreateFileMapping failed: " << GetLastError() << std::endl;
25         return 1;
26     }
27 
28     // 将共享内存映射到当前进程地址空间
29     SharedData* pSharedData = (SharedData*)MapViewOfFile(
30         hMapFile,               // 共享内存句柄
31         FILE_MAP_ALL_ACCESS,    // 可读可写
32         0, 0,                   // 偏移量
33         sizeof(SharedData)      // 映射大小
34     );
35 
36     if (pSharedData == NULL) {
37         std::cerr << "MapViewOfFile failed: " << GetLastError() << std::endl;
38         CloseHandle(hMapFile);
39         return 1;
40     }
41 
42     // 创建互斥量(用于同步)
43     HANDLE hMutex = CreateMutex(
44         NULL,                   // 默认安全属性
45         FALSE,                  // 初始状态为未锁定
46         L"MyMutex"              // 互斥量名称(需唯一)
47     );
48 
49     if (hMutex == NULL) {
50         std::cerr << "CreateMutex failed: " << GetLastError() << std::endl;
51         UnmapViewOfFile(pSharedData);
52         CloseHandle(hMapFile);
53         return 1;
54     }
55 
56     std::cout << "Writer started. Press Ctrl+C to exit..." << std::endl;
57     int count = 0;
58 
59     while (true) {
60         // 等待互斥量(加锁)
61         WaitForSingleObject(hMutex, INFINITE);
62 
63         // 写入数据
64         pSharedData->count = count;
65         sprintf_s(pSharedData->buffer, "Hello from writer %d", count);
66         std::cout << "Writer: Wrote " << count << std::endl;
67         count++;
68 
69         // 释放互斥量(解锁)
70         ReleaseMutex(hMutex);
71 
72         Sleep(100); // 等待100毫秒
73     }
74 
75     // 清理(通常不会执行到这里)
76     UnmapViewOfFile(pSharedData);
77     CloseHandle(hMapFile);
78     CloseHandle(hMutex);
79 
80     return 0;
81 }

2、Reader端

#include <iostream>
#include <Windows.h>

// 共享内存数据结构
struct SharedData {
    int count;
    char buffer[256];
};

int main() {
    // 打开共享内存
    HANDLE hMapFile = OpenFileMapping(
        FILE_MAP_ALL_ACCESS,    // 可读可写
        FALSE,                  // 不继承句柄
        L"MySharedMemory"       // 共享内存名称
    );

    if (hMapFile == NULL) {
        std::cerr << "OpenFileMapping failed: " << GetLastError() << std::endl;
        return 1;
    }

    // 将共享内存映射到当前进程地址空间
    SharedData* pSharedData = (SharedData*)MapViewOfFile(
        hMapFile,               // 共享内存句柄
        FILE_MAP_ALL_ACCESS,    // 可读可写
        0, 0,                   // 偏移量
        sizeof(SharedData)      // 映射大小
    );

    if (pSharedData == NULL) {
        std::cerr << "MapViewOfFile failed: " << GetLastError() << std::endl;
        CloseHandle(hMapFile);
        return 1;
    }

    // 打开互斥量
    HANDLE hMutex = OpenMutex(
        MUTEX_ALL_ACCESS,       // 访问权限
        FALSE,                  // 不继承句柄
        L"MyMutex"              // 互斥量名称
    );

    if (hMutex == NULL) {
        std::cerr << "OpenMutex failed: " << GetLastError() << std::endl;
        UnmapViewOfFile(pSharedData);
        CloseHandle(hMapFile);
        return 1;
    }

    std::cout << "Reader started. Press Ctrl+C to exit..." << std::endl;
    int count = -1;
    while (true) {
        // 等待互斥量(加锁)
        WaitForSingleObject(hMutex, INFINITE);
        //读取到序号相同的数据进行丢弃
        if (count == pSharedData->count)
        {
            ReleaseMutex(hMutex);
            continue;
        }
            
        // 读取数据
        std::cout << "Reader: Read " << pSharedData->count
            << ", " << pSharedData->buffer << std::endl;

        count = pSharedData->count;

        // 释放互斥量(解锁)
        ReleaseMutex(hMutex);

        Sleep(100); // 等待100毫秒
    }

    // 清理
    UnmapViewOfFile(pSharedData);
    CloseHandle(hMapFile);
    CloseHandle(hMutex);

    return 0;
}

 3、效果演示

 

posted @ 2025-03-14 14:53  左边的翼  阅读(398)  评论(0)    收藏  举报