At the operating system level, the virtual address space seen by each process is independent and there is no intersection between them. Therefore, you need to map different virtual addresses of multiple associated processes to the same physical address space through an intermediate Association.
MMAP is a function that maps a file (that is, the physical address space in the memory) to the address space of different processes.
I. Write
It is worth noting that MMAP requires the physical address space in the memory. Therefore, during the write operation, you need to load the file into the memory for the operation. Therefore, you need to perform the write operation after opening the file, this causes a page missing exception and maps the file to the memory.
Fd = open (argv [1], O_CREAT | O_RDWR | O_TRUNC, 00777 );
Lseek (fd, 4, SEEK_SET); <span style = "color: # ff0000;"> // The size here is preferably the size of the shared struct, load the entire required size into the memory
</Span> write (fd, "", 1 );
P_mmap = (int *) mmap (NULL, sizeof (int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
Close (fd );
* (P_mmap) = 1;
If you do not perform the write null operation, mmap ing will be performed directly, resulting in a segment error because the physical memory corresponding to the actual fd does not exist.
Ii. Read
The read process must call mmap after the write process. Otherwise, a segment error occurs, which is the same as the previous one.
Read Process Flow
Fd = open (argv [1], O_CREAT | O_RDWR, 0077 );
P_mmap = (int *) mmap (NULL, sizeof (int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
Printf ("data: % d \ n", (* (p_mmap )));
From the bofusi computer Column