c++ - 共享内存初始化和访问

标签 c++ c shared-memory

我正在编写一个使用共享内存的客户端-服务器程序。我创建了一个 shm.c 和 shm.h 以使客户端和服务器文件更好。但是,我想知道如何在下面的代码中使用 accessSHM 初始化共享内存(缺少,因为我不知道如果有人能解释一下我怎么能找到它,那将非常有帮助)。

    #include <stdbool.h>
    #include <time.h>
    #include <sys/mman.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <string.h>

    #include "shm.h"

    char * getTimeStamp() {
        time_t ltime = time(NULL);
        return strtok(ctime(&ltime), "\n");
    }

    int createSHM(char * shname)
    {
     if ((shmid = shmget(key, sizeof(msg), IPC_CREAT)) < 0) {
    perror("shmget");
    exit(1);
    }

} int loadSHM(char * shname) {

 if (shname< 0)
 {
 printf("shmget error\n");
 exit(1);
 }
    }


    SHMstruct * accessSHM(int fd) {

    }


    SHMstruct * initSHM(int fd, SHMstruct *data) {

    }


    void clearSHM(SHMstruct * shm)
    {
    int status = munmap(shm, sizeof(SHMstruct));
    if (status ==-1){
    fprintf(stderr, "Failure in clearSHM",strerror(errno));
    exit(errno);

    }
    }

    void closeSHM(int fd)
    {
    int status = close(fd);
    if (status ==-1){
    fprintf(stderr, "Failure in closeSHM",strerror(errno));
    exit(errno);
    }
    }


    void destroySHM(char * shname)
    {
    int status = shm_unlink (shname);
    if (status ==-1){
    fprintf(stderr, "Failure in destroySHM",strerror(errno));
    exit(errno);
    }
    }

shm.h

    #ifndef _shm_h_
#define _shm_h_

#include <stdbool.h>

#define SHNAME "/shmserver" // shared memory
#define MAX_TICKETS 10
#define MAX_SLEEP 1 // seconds

typedef struct SHM {
    int ticket;
    bool isTaken;
    bool soldOut;
} SHMstruct;

extern char * getTimeStamp();

extern int createSHM(char *shname);
extern int loadSHM( char *shname);

extern SHMstruct* initSHM( int fd, SHMstruct *data);
extern SHMstruct * accessSHM(int fd);

extern void clearSHM(SHMstruct * shm);
extern void closeSHM(int fd);
extern void destroySHM(char * shname);

#endif

最佳答案

共享内存是一个相当大的话题;仅仅说“这就是你打开的方式”真的是不够的。在自己编写之前,您可能需要确定是否需要这样做。

有几个库(包括 Boost 进程间库)提供了一个围绕创建和访问共享内存的包装器。在决定自己编写之前,您可能想先看看那里。

如果您不能使用 Boost(或其他一些库),并且真的必须自己编写一个,请记住您还需要提供一种同步(锁定)方式,以便读取和写入' 从多个进程同时发生。我建议查看其中一些库中的一些代码,甚至是 stackoverflow 上的代码:A simple shared memory application written on Linux了解基础知识,但只要了解这将需要相当多的代码才能获得一个可用的库。

关于c++ - 共享内存初始化和访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35414975/

相关文章:

c++ - 如何获得头文件中成员函数的正确代码覆盖率

c# - 实现共享内存时要考虑的要点

c++ - 调用 shmat 两次

c++ - 具有不同数据类型的纯虚拟方法

c++ - C++ 11线程在分离后是否自动销毁

控制台 I/O : printf & scanf not occurring in expected order

c - 使用多个 .c 文件构建 makefile 项目

c++ - 手动指定发送数据的网络接口(interface)

c++ - boost 的进程间段管理器分配器本身可以与其他进程共享吗?

c++ - virtual 关键字会影响基类方法的性能吗?