我正在为类分配一个作业,在该作业中,我们需要创建一些可以从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字段?