The parent-child and other related processes can also complete data communication through the mapping area established by mmap. However, the corresponding flag parameter flags should be specified when creating the mapping area: MAP_PRIVATE: (private mapping) exclusive mapping area for each parent-child process; MAP_SHARED: (shared mapping) shared mapping area for parent-child process.
//The parent process creates the mapping area, and then fork the child process. The child process modifies the content of the mapping area. Then, the parent process reads the content of the mapping area and checks whether it is shared.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/wait.h> int var = 100; //global variable int main(void) { int *p; pid_t pid; int fd; fd = open("temp", O_RDWR|O_CREAT|O_TRUNC, 0644); if(fd < 0){ perror("open error"); exit(1); } unlink("temp"); //Delete the temporary file directory entry so that it can be released. This file is not necessary to exist. It is only used to complete the mapping area for communication between parent and child processes, so unlink. ftruncate(fd, 4); //p = (int *)mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); p = (int *)mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); if(p == MAP_FAILED) { perror("mmap error"); exit(1); } close(fd); //After the mapping area is established, you can close the file pid = fork(); //Create child process if(pid == 0){ *p = 2000; var = 1000; printf("child, *p = %d, var = %d\n", *p, var); } else { sleep(1); printf("parent, *p = %d, var = %d\n", *p, var); wait(NULL); int ret = munmap(p, 4); //Release map area if (ret == -1) { perror("munmap error"); exit(1); } } return 0; }
[root @ localhost MMAP] ා / fork_mmap / / the parameter is specified as MAP_PRIVATE, which can communicate
child, *p = 2000, var = 1000
parent, *p = 0, var = 100 / / 0 is a random value. For uninitialized pointers, the content they point to is uncertain
[root @ localhost MMAP] ා / fork_mmap / / the parameter is specified as MAP_SHARED and cannot communicate
child, *p = 2000, var = 1000
parent, *p =2000, var = 100
Conclusion: parent-child process sharing: 1. Open file; 2. Map area established by MMAP (but MAP_SHARED must be used).