Search code examples
cforkposixshared-memorymmap

Why does this POSIX shared memory code give a segmentation fault?


#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;
}

I am basically looking to create some shared memory in the child process and access it from the parent.

In the child process, the mmap works fine. When I print using the pointer returned by mmap it does in fact print Hello, World!, but the same print gives a seg fault from the parent.


Solution

  • In the parent (pid != 0) you opened the object O_RDONLY, but mmapped it with PROT_WRITE, MAP_SHARED. Remove the | PROT_WRITE and you are fine. You might want to check the return values for errors the odd time.