clinuxshared-memory

Shared memory not granted permission to parent process


I have a problem in my C code about shared memory.

I have this C code that doesn't work as I expected:

#include "sys/ipc.h"
#include "sys/shm.h"

#include "unistd.h"
#include "sys/types.h"
#include "sys/wait.h"

#include "stdio.h"
#include "stdlib.h"

int main(){
    key_t key = ftok("shmfile.txt", 65);
    int shmid = shmget(key, sizeof(int), IPC_CREAT);
    if (fork() != 0){
        int * ptr = (int *) shmat(shmid, 0, 0); // This line returns -1
                            // This only happened
                            //  to parent
        printf("shmid parent = %d\n", shmid);
        perror("Error ");
        *ptr = 6;
        shmdt(ptr);
        wait(NULL);
        shmctl(shmid, IPC_RMID, NULL);
    }
    else{
        printf("shmid child = %d\n", shmid);
        int * ptr = (int *) shmat(shmid, 0, 0); // Works as expected
        printf("ptr address = %p\n", ptr);      
        shmdt(ptr);
        printf("Now child can exit normally");
    }
    return 0;
}

The result follows (gdb):

shmid parent = 45
Error : Permission denied
shmid child = 45
ptr address = 0xffffffffffffffff
Now child can exit normally
Program received signal SIGSEGV, Segmentation fault.
0x00005555555552d0 in main () at main_2.c:20
20          *ptr = 6;

I expected both the parent process and the child process to work fine. Only the child process exited normally. I am not sure what is the problem with the parent process. Thank you very much!

Update 1: The ptr in both parent and child process is always (void *) -1. I am not sure how to make the shmat() not to return that value.

Update 2: The file "shmfile.txt" is at the same location of the main excutable file.


Solution

  • You should specify permission used to create the shared memory.
    For instance using

    int shmid = shmget(key, sizeof(int), IPC_CREAT | 0666);
    

    From the documentation of shmget:

    In addition to the above flags, the least significant 9 bits of shmflg specify the permissions granted to the owner, group, and others. These bits have the same format, and the same meaning, as the mode argument of open(2). Presently, execute permissions are not used by the system.

    With this modification your code is running.

    Ideone