進程間通信-共享內存以及使用案例

在這裏插入圖片描述
服務器與客戶端通過共享內存進行通信
1.common.h

#ifndef __COMMON_H
#define __COMMON_H

#define TEXT_LEN 2048

// 共享內存的數據結構
struct SharedMemEntry
{
    bool can_read; // 是否可以讀取共享內存,用於進程同步
    char message[TEXT_LEN];
};

#endif // __COMMON_H

2.server.cpp

#include "common.h"
#include <iostream>
#include <chrono>
#include <sys/shm.h>
#include <unistd.h>

int main()
{
    SharedMemEntry *entry;

    //1、申請共享內存
    int shared_mem_id = shmget(1, sizeof(SharedMemEntry), 0600 | IPC_CREAT);
    if (shared_mem_id == -1)
    {
        std::cout << "Create shared memory error" << std::endl;
        return -1;
    }

    // 2、連接到當前進程空間/使用共享內存
    entry = (SharedMemEntry *)shmat(shared_mem_id, 0, 0);
    entry->can_read = false;
    while (true)
    {
        if (entry->can_read)
        {
            std::cout << "Received message:" << entry->message << std::endl;
            entry->can_read = false;
        }
        else
        {
            std::cout << "Entry can not be read. Sleep 1s." << std::endl;
            sleep(1);
        }
    }
    // 3、脫離進程空間
    shmdt(entry);
    // 4、刪除共享內存
    shmctl(shared_mem_id, IPC_RMID, 0);
    return 0;
}
  1. client.cpp
#include "common.h"
#include <sys/shm.h>
#include <iostream>
#include <cstring>

int main()
{
    SharedMemEntry *entry;

    // 1、申請共享內存
    int shmid = shmget(1, sizeof(SharedMemEntry), 0600 | IPC_CREAT);
    if (shmid == -1)
    {
        std::cout << "Create shared memory failer" << std::endl;
        return -1;
    }

    // 連接到當前進程空間
    entry = (SharedMemEntry *)shmat(shmid, 0, 0);
    entry->can_read = false;
    char buffer[TEXT_LEN];
    while (true)
    {
        if (!entry->can_read)
        {
            std::cout << "input message >>>";
            fgets(buffer, TEXT_LEN, stdin);
            strncpy(entry->message, buffer, TEXT_LEN);
            std::cout << "send message: " << entry->message << std::endl;
            entry->can_read = true;
        }
    }
    shmdt(entry);
    shmctl(shmid, IPC_RMID, 0);
}```

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章