Данные общей памяти с использованием файла заголовка - PullRequest
0 голосов
/ 09 марта 2019

Я делаю задание для класса, в котором нам нужно создать общую память, доступ к которой можно получить из 2 разных программ. Существует заголовочный файл с именем shm.h , в котором содержатся данные, которыми мы должны обмениваться. Пока мой код выглядит так.

shm.h

#ifndef SHM_H
#define SHM_H
//<Define an enum called StatusEnus with the enumerations "INVALID", "VALID" 
and "CONSUMED">
#define enum StatusEnus{INVALID, VALID, CONSUMED} StatusEnus

//<Define a typedef structure with the enum above and an "int" variable 
//called "data">

#define struct ShmData{StatusEnus status; int data;}ShmData;
#define SIZE 8

#endif

server_template

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
#include "shm.h"

int main(int argc, char* argv[])
{   
    //void* memPtr;
    int retVal = 0;

    //<Confirm argc is 2 and if not print a usage string.>
    if(argc != 2){
        printf("Please enter 2 arguments5");
    }

    /*<Use the POSIX "shm_open" API to open file descriptor with 
        "O_CREAT | O_RDWR" options and the "0666" permissions> */
        //returns -1 on error
        int file = shm_open("sharedMem", O_CREAT | O_RDWR, 0666);
            if (file == -1) retVal =-1;

    /*<Use the "ftruncate" API to set the size to the size of your 
        structure shm.h>*/
    retVal = ftruncate(file,SIZE);

    //<Use the "mmap" API to memory map the file descriptor>
    void* data = mmap(0, SIZE,PROT_WRITE | PROT_WRITE, MAP_SHARED, file, 0);

    /*<Set the "status" field to INVALID>
    <Set the "data" field to atoi(argv[1])>
    <Set the "status" field to VALID>*/
    ShmData->status = INVALID;
    ShmData->data = atoi(argv[1]);
    ShmData->status = VALID;


  printf("[Server]: Server data Valid... waiting for client\n");

  while(ShmData->status != CONSUMED)
    {
      sleep(1);
    }

  printf("[Server]: Server Data consumed!\n");

  /*<use the "munmap" API to unmap the pointer>

  <use the "close" API to close the file Descriptor>

  <use the "shm_unlink" API to revert the shm_open call above>*/

  printf("[Server]: Server exiting...\n");


  return(retVal);

}

Таким образом, моя цель - получить доступ к полям, таким как ShmData-> StatusEnus, с сервера, а также получить доступ к этим файлам из отдельной программы. Тем не менее, в настоящее время я продолжаю получать ошибки, связанные с замедлением ShmData. Как мне убедиться, что создаваемая мной общая память содержит поля enum и int из моей структуры?

...