A. POSIX shared memory implementation
Shared memory is a piece of memory shared between processes. Is the fastest kind of IPC communication organization. The POSIX shared memory mechanism is mainly implemented through the memory Mapping (MMAP) mechanism.
Shared memory between processes uses the following fixed steps:
1. Create a shared memory
int Shm_open (const char *name, int oflag, mode_t mode);
Name is the shared memory name, and each process finds the same memory by name.
Oflag, is this memory attribute. Similar to file properties. With O_rdwr/o_rdonly/o_creat, the first time you create shared memory you must have a o_creat flag bit.
Mode, is the permission code.
When it opens successfully, it will create a virtual file/DEV/SHM/SHM. XXXX, where xxxx is name
Example: int fd = Shm_open ("Test", o_rdwr,666);
The/dev/shm/shm.test file will be created.
After the Shm_open succeeds, a file descriptor FD is returned. You can understand that you are allocating a space in the kernel and assigning an FD number to the application.
Note here that if a process has created a shared memory, the other processes on the other side will open the shared memory using only
Shm_open (name,flag,0); And
2. Set the memory size.
int ftruncate (int fd, off_t length);
Ftruncate operation of the FD can be a file open after the FD, but also shm_open open FD.
The normal file will be forced by ftruncate to length (not enough to add 0 space, more than is truncated
If shared memory, it will indicate that the shared memory is set to length size.
If setting Ftruncate returns 0