Advantages of shared memory:
1. Data is transmitted between processes without passing through the kernel, that is, data is copied without calling the system to achieve fast and efficient data transmission.
2. continued with the kernel
* Nix shared memory has two sets of Apis: POSIX and System V.
The main difference between the two is the size of the shared memory.
1. POSIX shared memory size can be modified at any time through the ftruncate Function
2. The System V shared memory size has been determined at the time of creation, and the maximum value varies depending on the system.
POSIX shared memory
# Include <sys/Mman. h> (MMAP, munmap, msync, shm_open, shm_unlink)
MMAP, the main function
Void * MMAP (void * ADDR, size_t Len, int Prot, int flags, int FD, off_t offset)
The function maps a handle to the memory. The handle can be an open file handle or a shm_open shared memory area object.
* In view of all files in Nix, shm_open creates a file object in the/dev/SHM directory and returns the object descriptor.
MMAP maps the handle to the memory as the underlying Supporting Object of the shared memory, so that the memory can be shared between processes without reading or writing. It is estimated that the more primitive method for transferring data between * nix processes is to read and write a file between processes. However, frequent open, read, write, and lseek system calls consume too much computing resources. So I thought of ing the file handle to the memory, which improves the efficiency of data transmission between processes.
Msync
After the memory in the memory ing area is modified, the Kernel updates the file content at a certain time point. To ensure that the file is updated, call the msync function. The file update can be synchronous (ms_sync) or asynchronous (ms_async ). (The function write Update file is also called here)
System V shared memory
# Include <sys/SHM. h> (shmget, shmat, shmdt, shmctl)
Because System V's shared memory has a size limit, you can consider using the shared memory array to solve this problem. Although the size of the array is also limited by the amount of shared memory that a process can obtain, it can alleviate the problem that a single shared memory of System V is too small.