共享内存|使用共享内存存储结构体实现进程通信及快速解析

结构体定义文件

#include <iostream>
#include <cstring>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>

struct SharedData {
    int id;
    char name[100];
};

进程一

int main() {
    const char* shm_name = "MySharedMemory";
    const int SIZE = sizeof(SharedData);

    int shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666);
    if (shm_fd == -1) {
        perror("shm_open");
        return 1;
    }

    // Set the size of the shared memory object
    ftruncate(shm_fd, SIZE);

    // Memory map the shared memory object
    void* ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (ptr == MAP_FAILED) {
        perror("mmap");
        return 1;
    }

    // Create and write the structure to shared memory
    SharedData* data = new(ptr) SharedData; // Placement new
    data->id = 1;
    strcpy(data->name, "SharedMemoryExample");

    std::cout << "Data written to shared memory: " << data->id << ", " << data->name << std::endl;

    // Unmap and close are typically done in a cleaner way or in another part of the program
    munmap(ptr, SIZE);
    close(shm_fd);

    return 0;
}

进程二

int main() {
    const char* shm_name = "MySharedMemory";
    const int SIZE = sizeof(SharedData);

    int shm_fd = shm_open(shm_name, O_RDONLY, 0666);
    if (shm_fd == -1) {
        perror("shm_open");
        return 1;
    }

    // Memory map the shared memory object
    void* ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
    if (ptr == MAP_FAILED) {
        perror("mmap");
        return 1;
    }

    // Read the structure from shared memory
    SharedData* data = (SharedData*) ptr;
    std::cout << "Read from shared memory: ID = " << data->id << ", Name = " << data->name << std::endl;

    // Cleanup
    munmap(ptr, SIZE);
    close(shm_fd);

    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值