Trying to write to an int in shared memory (using mmap) with a child process

痞子三分冷 提交于 2019-11-30 15:20:20

Your problem is the flags passed into mmap(), you want MAP_SHARED.

int * shared = mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); 

Works as expected with the code below

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

int main(void) {
    int * shared = mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); 
    pid_t child;
    int childstate;
    printf("%d\n", *shared);
    if((child=fork())==0){
            *shared = 1;
            printf("%d\n", *shared);
            exit(0);
    }
    waitpid (child, &childstate, 0); 
    printf("%d\n",*shared);
}

Output:

0
1
1

mmap man page may help you if you haven't already found it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!