共享内存

win;写和读;来源于网络

#include <iostream>
#include <Windows.h>
// 共享内存数据结构,并保持单字节对齐
#pragma pack(push, 1)
struct SharedData {
    int count;
    char buffer[256];
};
#pragma pack(pop)

int main()
{
    int a = sizeof(SharedData);
    std::cout << "the value of a is:" << a << std::endl;
    // 创建或打开共享内存
    HANDLE hMapFile = CreateFileMapping(
        INVALID_HANDLE_VALUE,   // 使用物理内存而非文件
        NULL,                   // 默认安全属性
        PAGE_READWRITE,         // 可读可写
        0,                      // 内存大小高位
        sizeof(SharedData),     // 内存大小低位
        L"MySharedMemory"       // 共享内存名称(需唯一)
    );

    if (hMapFile == NULL) {
        std::cerr << "CreateFileMapping 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 = CreateMutex(
        NULL,                   // 默认安全属性
        FALSE,                  // 初始状态为未锁定
        L"MyMutex"              // 互斥量名称(需唯一)
    );

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

    std::cout << "Writer started. Press Ctrl+C to exit..." << std::endl;
    int count = 0;

    while (true) {
        // 等待互斥量(加锁)
        WaitForSingleObject(hMutex, INFINITE);

        // 写入数据
        pSharedData->count = count;
        sprintf_s(pSharedData->buffer, "Hello from writer %d", count);
        std::cout << "Writer: Wrote " << count << std::endl;
        count++;

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

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

    // 清理(通常不会执行到这里)
    UnmapViewOfFile(pSharedData);
    CloseHandle(hMapFile);
    CloseHandle(hMutex);

    return 0;
}
#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;
}

Linux端

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

// 共享数据结构(保持与写入端一致)
struct SharedData {
    int count;
    char buffer[256];
};

int main() {
    // 1. 打开共享内存对象
    int shm_fd = shm_open("/my_shared_mem", O_RDONLY, 0666);
    if (shm_fd == -1) {
        perror("shm_open failed");
        return 1;
    }

    // 2. 内存映射
    SharedData* shared_data = (SharedData*)mmap(
        NULL, sizeof(SharedData),
        PROT_READ,
        MAP_SHARED, shm_fd, 0
    );
    if (shared_data == MAP_FAILED) {
        perror("mmap failed");
        close(shm_fd);
        return 1;
    }

    // 3. 打开信号量
    sem_t* sem = sem_open("/my_shm_sem", 0);
    if (sem == SEM_FAILED) {
        perror("sem_open failed");
        munmap(shared_data, sizeof(SharedData));
        close(shm_fd);
        return 1;
    }

    std::cout << "Reader started (PID: " << getpid() << ")" << std::endl;
    
    int last_count = -1;
    while (true) {
        // 4. 获取信号量(加锁)
        sem_wait(sem);

        // 5. 检查是否为重复数据
        if (last_count != shared_data->count) {
            // 6. 读取新数据
            std::cout << "Reader: Count=" << shared_data->count 
                     << ", Message=" << shared_data->buffer << std::endl;
            last_count = shared_data->count;
        }

        // 7. 释放信号量(解锁)
        sem_post(sem);

        usleep(100000); // 等待100毫秒
    }

    // 8. 清理资源(实际运行时通常不会执行到这里)
    munmap(shared_data, sizeof(SharedData));
    close(shm_fd);
    sem_close(sem);

    return 0;
}
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <semaphore.h>

// 共享数据结构(保持与读取端一致)
struct SharedData {
    int count;
    char buffer[256];
};

int main() {
    // 1. 创建或打开共享内存对象
    int shm_fd = shm_open("/my_shared_mem", O_CREAT | O_RDWR, 0666);
    if (shm_fd == -1) {
        perror("shm_open failed");
        return 1;
    }

    // 2. 设置共享内存大小
    if (ftruncate(shm_fd, sizeof(SharedData)) == -1) {
        perror("ftruncate failed");
        close(shm_fd);
        return 1;
    }

    // 3. 内存映射
    SharedData* shared_data = (SharedData*)mmap(
        NULL, sizeof(SharedData),
        PROT_READ | PROT_WRITE,
        MAP_SHARED, shm_fd, 0
    );
    if (shared_data == MAP_FAILED) {
        perror("mmap failed");
        close(shm_fd);
        return 1;
    }

    // 4. 创建/打开信号量(用于进程同步)
    sem_t* sem = sem_open("/my_shm_sem", O_CREAT, 0666, 1);
    if (sem == SEM_FAILED) {
        perror("sem_open failed");
        munmap(shared_data, sizeof(SharedData));
        close(shm_fd);
        return 1;
    }

    std::cout << "Writer started (PID: " << getpid() << ")" << std::endl;
    
    int counter = 0;
    while (true) {
        // 5. 获取信号量(加锁)
        sem_wait(sem);

        // 6. 写入数据
        shared_data->count = counter;
        snprintf(shared_data->buffer, sizeof(shared_data->buffer),
                "Message %d from writer", counter);
        std::cout << "Wrote: " << counter << std::endl;
        counter++;

        // 7. 释放信号量(解锁)
        sem_post(sem);

        usleep(500000); // 写入间隔500ms
    }

    // 8. 清理资源(实际运行时通常不会执行到这里)
    munmap(shared_data, sizeof(SharedData));
    close(shm_fd);
    sem_close(sem);
    shm_unlink("/my_shared_mem");
    sem_unlink("/my_shm_sem");

    return 0;
}

 

posted on 2025-07-14 17:09  邗影  阅读(6)  评论(0)    收藏  举报

导航