共享内存指针在尝试设置值时导致段错误

问题描述 投票:0回答:1

我试图创建一个进程来访问另一个进程创建的共享内存段。一切工作正常,我可以获得共享内存段的 id、指向该段的指针,并且我可以从中分离进程。当我尝试使用 shmat 给出的指针在内存上写入单个字符后,问题就开始了。 如果我尝试使用指针读取或写入并不重要,它会引发段错误。

这是创建共享内存的进程的代码:

#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include "shmlib.h"

extern int shmsize;

int main(int argc, char const *argv[])
{
    int shmid;        // Variable con el identificador del espacio en memoria

    // Le pedimos al usuario que ingrese cuanta memoria va a querer
    printf("Ingrese la cantidad de espacios en memoria a usar: ");
    scanf("%d", &shmsize);
    shmid = getMemoryBlock();
    if (shmid<0){
        printf("Error al inicializar la memoria");
        exit(1);
    };

    // Le mostramos al usuario el id del espacio de memoria compartida.
    printf("El espacio de memoria con id %d fue creado exitosamente.", shmid);
    return 0;
}

这是访问共享内存的进程的代码:

#include <stdio.h>
#include <stdlib.h>
#include "shmlib.h"
#include <sys/ipc.h>

extern int shmsize;

int main(int argc, char const *argv[])
{
    int size, algoType, sleepTime, numLines;
    char* mem;    
    if (argc!=5){
        printf("Argumentos insuficientes.\n");
        exit(1);
    }
    size = atoi(argv[1]);
    algoType = atoi(argv[2]);
    sleepTime = atoi(argv[3]);
    numLines = atoi(argv[4]);
    shmsize=size;

    mem = attachToMemory();
    if (mem==NULL){
        printf("No se puede acceder a la memoria compartida\n");
        exit(1);
    }
    
    char *it;
    it = mem;
    *it = 'c'; //This causes the segfault

    int res = detachFromMemory(mem);
    if (res==true){
        printf("Se solto la memoria compartida");
    }
    return 0;
}

这是 shmlib.c 的代码,其中包含 AttachToMemory 和 detachFromMemory

#include "shmlib.h"

int shmsize = 0;
const key_t key = 4629;

int getMemoryBlock(){
    return shmget(key, shmsize,  IPC_CREAT | 0666);
}

char * attachToMemory(){
    int shmid = getMemoryBlock();
    char *result;
    if (shmid==-1){
        return NULL;
    }

    result = shmat(shmid, NULL, 0);
    if (result == (char *)-1){
        return NULL;
    }
    return result;
}


bool detachFromMemory(char * mem){
    return (shmdt(mem)!= -1);
}
bool destroyMemory(){
    int shmid = getMemoryBlock();

    if (shmid==-1){
        return NULL;
    }

    return (shmctl(shmid, IPC_RMID, NULL)!=-1);
}

我尝试更改权限以查看是否是问题的一部分,但没有成功。我还尝试查看它 shmat 抛出任何错误,但 errno 总是返回 0。

所以我在这里寻求帮助。

c linux pointers segmentation-fault shared-memory
1个回答
0
投票

shmsize 为 0,这可能是问题所在。

© www.soinside.com 2019 - 2024. All rights reserved.