如何访问和修改共享内存中的结构?

时间:2018-06-12 09:08:12

标签: c segmentation-fault structure system-calls shared-memory

我遇到共享内存问题。我想在共享内存中分配一个结构,我也想访问它,但是当我尝试修改结构时,我就会出现分段错误。

这是代码:

typedef struct Status{
int grandson;
int id_string;
}S;

void padre(char *filename){
   S *p_status;
   S status;
   int shm_idS1;
   int shm_idS2;
   char *S1; //Area di memoria condivisa
   char *S2;
   char id;

   //S1
   id='A';
   shm_idS1=attach_segments(filename,id);
   printf("SHMID:%d \n", shm_idS1);

   //Link processo all'area di memoria condivisa
   if(p_status = shmat(shm_idS1, NULL, 0)== -1){
      perror("SHMAT");
      exit(1);}


   //inizialitation structure
    p_status->id_string = 0; //HERE I've Segmentation fault

}



int attach_segments(char *filename, char id){
   int shm_id;

   //Variabili creazione mem condivisa
   key_t key;
   char *data;

   //Variabili File_input
   int sizeFileInput;
   struct stat st;
   stat(filename, &st);
   sizeFileInput = st.st_size;

   //Creo Chiave dato un percorso
   if ((key = ftok(".", id)) == -1){
        perror("ftok");
        exit(1);}

   printf("size:%d\n",sizeFileInput);//

   //Creo segmento memoria condivisa con la chiave appena generata  
   if((shm_id=shmget(key, sizeof(struct Status) + sizeFileInput,0666 | IPC_CREAT |IPC_EXCL))==-1){
       perror("SHMGET");
       exit(1);}

    return shm_id;
}

我尝试使用gdb进行调试,问题是p_status点之后shmat变量0x00 为什么呢?

0 个答案:

没有答案