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

I play with code that requires communication between a parent and a forked child process. I created an int in shared memory before the fork, but any changes I make to the child process do not seem to affect the int when accessing the parent process. Here is 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 returns 0.

In my real program, the structure will be split instead of int, but if I can understand this piece of code, I think the rest should fall into place.

, C. , , , . , :). , - - ? .

+4
1

- , mmap(), MAP_SHARED.

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

, ,

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

:

0
1
1

mmap man page , .

+7

All Articles