进程间共享内存通信(信号量同步)c++

运行环境:ubuntu18.4
进程间共享内存通信,通过信号量实现进程同步。
创建writer进程,reader进程,writer会每隔一段时间向共享内存写入新的数据,而reader会阻塞地等待并读取这些数据。

上代码:

共享资源定义文件 SharedResource.h

// SharedResource.h 文件

#ifndef SHAREDRESOURCE_H
#define SHAREDRESOURCE_H

const char* const SHARED_MEMORY_NAME = "/my_shared_memory";
const char* const SEM_WRITE_NAME = "/sem_write";
const char* const SEM_READ_NAME = "/sem_read";
const int BUFFER_SIZE = 1024; // 定义缓冲区大小

#endif // SHAREDRESOURCE_H

writer.cpp 文件

// writer.cpp 文件

#include 
#include 
#include 
#include 
#include 
#include 
#include "SharedResource.h"

int main() {
    int shm_fd = shm_open(SHARED_MEMORY_NAME, O_CREAT | O_RDWR, 0666);
    if (shm_fd == -1) {
        perror("shm_open");
        return 1;
    }
    ftruncate(shm_fd, BUFFER_SIZE);
    
    void* mapped = mmap(0, BUFFER_SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (mapped == MAP_FAILED) {
        perror("mmap");
        close(shm_fd);
        return 1;
    }

    sem_t* sem_write = sem_open(SEM_WRITE_NAME, O_CREAT, 0666, 1);
    sem_t* sem_read  = sem_open(SEM_READ_NAME, O_CREAT, 0666, 0);

    for (int i = 0;; ++i) {
        // 写入前等待
        sem_wait(sem_write);

        snprintf(static_cast<char*>(mapped), BUFFER_SIZE, "Data %d from writer process %d", i, getpid());
        
        // 写入后允许读取
        sem_post(sem_read);

        sleep(2); // 休眠以模拟长时间运行情况
    }

    // 清理
    munmap(mapped, BUFFER_SIZE);
    close(shm_fd);
    sem_close(sem_write);
    sem_close(sem_read);

    return 0;
}

reader.cpp 文件

// reader.cpp 文件

#include 
#include 
#include 
#include 
#include 
#include "SharedResource.h"

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

    void* mapped = mmap(0, BUFFER_SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
    if (mapped == MAP_FAILED) {
        perror("mmap");
        close(shm_fd);
        return 1;
    }

    sem_t* sem_write = sem_open(SEM_WRITE_NAME, 0);
    sem_t* sem_read  = sem_open(SEM_READ_NAME, 0);

    while (true) {
        // 读取前等待
        sem_wait(sem_read);

        // 读取共享内存数据
        std::cout << "Data read from memory: " << static_cast<const char*>(mapped) << std::endl;

        // 读取后允许写入
        sem_post(sem_write);

        sleep(1); // 休眠以模拟长时间运行情况
    }

    // 清理
    munmap(mapped, BUFFER_SIZE);
    close(shm_fd);
    sem_close(sem_write);
    sem_close(sem_read);

    return 0;
}

编译程序

g++ writer.cpp -o writer -lrt -lpthread
g++ reader.cpp -o reader -lrt -lpthread

在一个终端中运行数据写入文件

./writer

在另一个终端中运行读文件

./reader

你可能感兴趣的:(c++,开发语言)