c - 为什么这个 POSIX 共享内存代码会出现段错误?

标签 c fork posix shared-memory mmap

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/mman.h>

int main()
{
    const int SIZE = 500;
    const char *name = "name";
    int fd;
    char *ptr = NULL;
    pid_t pid;
    pid = fork();

    if (pid < 0) {
        fprintf(stderr, "Fork Failed");
        return 1;
    }
    else if (pid == 0) {
        fd = shm_open(name,O_CREAT | O_RDWR,0666);
        ftruncate(fd, SIZE);
        ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        sprintf(ptr, "%s", "Hello, World!\n");
        return 0;
    }
    else {
        wait(NULL);
        fd = shm_open(name, O_RDONLY, 0666);
        ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        printf("%s\n", (char *)ptr);
    }
    return 0;
}

我基本上是想在子进程中创建一些共享内存并从父进程访问它。

在子进程中,mmap 工作正常。当我使用 mmap 返回的指针打印时,它实际上打印了 Hello, World!,但同样的打印给出了来自父级的段错误。

最佳答案

在父级 (pid != 0) 中,您打开了对象 O_RDONLY,但使用 PROT_WRITE、MAP_SHARED 对其进行了映射。删除 | PROT_WRITE,你很好。 您可能想偶尔检查错误的返回值。

关于c - 为什么这个 POSIX 共享内存代码会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53240270/

相关文章:

shell - 如何在中断时杀死当前shell的所有 child ?

c - Linux 中的 fork 和 setsid() 的使用

c - fork() 在这个 C 程序中是如何工作的?

c - 使用 POSIX 定时器后程序不退出

c - Telnet "wont echo"被windows机器抑制

python - 如何让设置工具安装 github 分支的 PyPI 包?

c - 关于sighandler的频率

c - sprintf 与 %*.s 格式说明符一起使用时写入空白字符串

c - 如何读取远程 INI 文件

c - MPI 单面 : Exclusive Lock with MPI_Win_lock_all