Shared memory can be said to be the most useful interprocess communication and the fastest form of IPC because processes can read and write directly to memory without requiring any copy of the data. For communication like pipelines and Message Queuing, four copies of the data are required in the kernel and user space, while shared memory copies only two times: one from the input file to the shared memory area and the other from the shared memory area to the output file. In fact, when sharing memory between processes, the mappings are not always read and written, and when there is new communication, the shared memory area is again established. Instead, keep the shared area until the communication is complete so that the data content is kept in shared memory and not written back to the file. Content in shared memory is often written back to the file when the mapping is released. Therefore, the use of shared memory communication mode is very high efficiency.
I. Traditional file access
Unix's traditional way of accessing files is to open them with open, and if more than one process accesses the same file, each process contains that in its own address space.
A copy of the file, which unnecessarily wastes storage space. The following figure illustrates the case where two processes read the same page of a file at the same time. The system is going to read the page from disk to high
Speed buffer, each process then performs a copy operation within the memory to read data from the cache to its own address space.
Two. Shared Storage mappings
Now consider another approach: both process A and process B map the page to its own address space, and when process a first accesses the data in that page, it generates a
A page break. The kernel then reads the page into memory and updates the page table to point to it. Later, when process B accesses the same page and there are pages broken, the page is already
Memory, the kernel only needs to point the page table registration entry of process B to the secondary page. As shown in the following illustration: