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

故事扮演 提交于 2019-11-29 22:36:30

问题


I'm playing around with some code that requires communication between a parent and a forked child process. I've created an int in shared memory before the fork, but any changes I make with the child process don't seem to affect the int when accessed by the parent process. Here's a piece of code that illustrates my problem.

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

Although the child process sets the value of 'shared' to 1, this program outputs 0.

In my actual program a struct will be shared instead of an int, but if I can figure out this code snippet, I think the rest should fall into place.

I'm by no means an experienced programmer, and I'm a bit unfamiliar with C. I've spent hours trying to figure this out and read dozens of pages which say it should be a simple process. To be honest, it's been a heavy blow to my self esteem :) . I'm sure I'm just missing some small detail - can anybody point it out to me? Thanks in advance for your time.


回答1:


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.



来源:https://stackoverflow.com/questions/19672778/trying-to-write-to-an-int-in-shared-memory-using-mmap-with-a-child-process

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