读取器尝试从共享内存读取时出现分段错误错误

时间:2020-03-08 10:04:08

标签: c linux unix ipc shared-memory

我试图了解System V共享内存API。我创建了一个小程序,其中一个程序写入共享内存,另一个程序从共享内存读取。但是由于某种原因,我遇到了一个错误:

segmentation fault: 11

当我尝试从共享内存中读取时。我找不到原因。

这是我所做的:

以下程序将写入共享内存。

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

    struct shm_seg {
        char *buf;
    };

    int main() {
        int shmid = shmget(1, sizeof(struct shm_seg), IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

        if(shmid == -1) {
            printf("Failed to fetch the shared memory id");
            exit(-1);
        }

        struct shm_seg *shm_segp = shmat(shmid, NULL, 0);

        if(shm_segp == (void*)-1) {
            printf("Failed to attach shared memory to the shared memory id");
            exit(-1);
        }

        while (1) {
            shm_segp->buf = "hello";
        }

        if(shmdt(shm_segp) == -1) {
            printf("Failed to detach the shared memory");
            exit(-1);
        }

        if(shmctl(shmid, IPC_RMID, 0) == -1) {
            printf("Failed to delete a shared memory object");
            exit(-1);
        }
    }

和以下代码尝试从共享内存中读取。

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

struct shm_seg {
    char *buf;
};

int main() {
    int shmid = shmget(1, 0, 0);

    if(shmid == -1) {
        printf("Failed to fetch the shared memory id");
        exit(-1);
    }

    struct shm_seg *shm_segp = shmat(shmid, NULL, SHM_RDONLY);

    if(shm_segp == (void*)-1) {
        printf("Failed to attach shared memory to the shared memory id");
        exit(-1);
    }

    int i = 0;
    while(i < 100 ) {
        printf("%s\n",shm_segp->buf);
        i++;
    }


    if(shmdt(shm_segp) == -1) {
        printf("Failed to detach the shared memory");
        exit(-1);
    }
}

上面的阅读器程序导致Segmentation fault: 11错误。这可能是什么原因?我做错了什么事?

1 个答案:

答案 0 :(得分:3)

        shm_segp->buf = "hello";

该代码没有意义。这会将指针放在共享内存中。

您的代码将一个指向字符串常量的指针从一个程序传递到另一个程序。然后,它在另一个程序中取消引用该指针。但这有什么意义呢?它是指向另一个程序的内存空间的指针,对其他程序没有任何意义。

如果要将数据从一个程序传递到另一个程序,则实际上需要将要传递的数据放入共享内存中。如果数据本身不在共享内存中,则将指针指向共享内存不会有任何好处!