繁体   English   中英

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

[英]Segmentation fault error as the reader tries to read from the 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错误。 这可能是什么原因? 我做错了什么?

        shm_segp->buf = "hello";

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM