0

i'm tryng to create a pointer-based queue in shared memory

This my enqueue function

void enqueue(queue *q, int k) {   
    _queueNode *temp = mmap(NULL, sizeof(_queueNode), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    temp->key = k;
    temp->next = NULL;  
    
    if (q->rear == NULL) { 
        q->front = q->rear = temp;
    }
    else {
        q->rear->next = temp; 
        q->rear = temp;
    }

    q->length++;
}

_queueNode struct

typedef struct queueNode { 
    int key; 
    struct queueNode *next; 
} _queueNode; 

Enqueue in the parent process all works fine, but when i enqueue in the child process only works on it, and got a segmentation fault when i read the changes in the parent process. My main is like this

queue *q = newqueue();
enqueue(q, 1);
enqueue(q, 2);
enqueue(q, 3);

if (fork() == 0) {
    enqueue(q, 4);
    printf("child: ");
}
else {
    wait(NULL);
    printf("parent: ");
}
printqueue(q);

and i'm getting this output

child: [4, 3, 2, 1]
Segmentation fault (core dumped)
André Kuljis
  • 90
  • 1
  • 9
  • `MAP_SHARED | MAP_ANONYMOUS` means that the memory is shared with the *children* of the current process. There's no way the parent process could access that memory, it's simply not mapped into the parent process. You might want to consider [POSIX shared memory](https://man7.org/linux/man-pages/man7/shm_overview.7.html). – Some programmer dude Nov 01 '20 at 03:12
  • @Someprogrammerdude hmm, Is there no flag that allows the parent process to access a child-created memory? – André Kuljis Nov 01 '20 at 16:17

0 Answers0