Linux provides us with a wealth of internal process communication mechanisms, including shared memory, memory-mapped files, first-in-first out (FIFO), interface (sockets), and various identities for synchronization. In this article, we mainly discuss shared memory and memory-mapped file technology.
In general, internal process communication (interprocess communication), or IPC, is the communication between two or more processes and two or more than two threads. Each IPC mechanism has different strengths or weaknesses, but none of the IPC mechanisms contain built-in synchronization methods. As a result, programmers need not only synchronize their own programs, but also develop communication protocols themselves in order to exploit the IPC mechanism.
Shared memory
Using shared memory and using malloc to allocate memory areas is similar. The way to use shared memory is:
1. Allocate memory areas for a process/thread using Shmget.
2. Use Shmat to place one or more processes/threads in shared memory, you can also use Shmctl to gain information or control shared areas.
3. Use SHMDT to detach from the shared area.
4. Use Shmctl to deallocate space
Here's an example:
Establish shared memory area
intshared_id;
char *region;
Const INTSHM_SIZE = 1024;
shared_id = Shmget (ipc_private,//guaranteed to use unique ID
shm_size,
ipc_creat | IPC_EXCL |//Create a new memory area
S_IRUSR | S_IWUSR///enables current users to read and write this area
//cross process or build process.
Place the newly created memory area into the process/thread
region = (char*) shmat (segment_id, 0, 0);
Other program code
...
Separate processes/threads from
shmdt (region);
Destroy the shared memory area
Shmctl (shared_id, Ipc_rmid, 0);
Shared memory is the fastest IPC method in Linux. He is also a two-way process in which any process in a shared area can read and write memory. The disadvantage of this mechanism is that its synchronization and protocol are not controlled by programmers, and you must ensure that the handle is passed to the child processes and threads.