Linux System V and POSIX IPC Examples
Introduction
System V Private IPC
Shared Memory
Semaphores
Message Queues
Makefile
Introduction
Some recent tasks at work highlighted some obvious gaps in my working knowledge of Linux inter-process communication (IPC). I spent some personal time brushing up on things I had used before and learning about some mechanisms that I had not used before. I am not discussing pipes or sockets here; I am discussing message queues, semaphores, and shared memory. The System V and POSIX specifications have different APIs for using basically the same three IPC mechanisms. I am not exploring every nuance of each API or comparing performance. My goal was simply to demonstrate each IPC mechanism for each API in a set of very simple programs. I show the programs side by side where appropriate, but the code is also available in ipc_sysv_posix.zip.
My test system runs Fedora 20 Linux with the latest updates as of August 9, 2015. The Makefile at the end shows the compile commands.
System V Private IPC
The System V API allows for private, unnamed, in-memory IPC mechanisms to be shared between parent and identical forked child processes. The processes must be the same and the IPC mechanisms will not be passed along to different exec'd processes. System V IPC among different processes requries a file system path name and a project name to identify a shared IPC resource. So, System V IPC mechanisms can all be named or unnamed. POSIX supports named (sem_open) and unnamed (sem_init) semaphores, but message queues (mq_open) and shared memory (shm_open) must be named. Here I demonstrate private unnamed System V shared memory IPC between a parent process and a forked child process. The same key=IPC_PRIVATE approach also applies to the other System V IPC mechanisms, so I only wrote an example program for private unnamed shared memory.
Shared Memory
process | System V | POSIX |
parent |
|
|
child |
|
|
Semaphores
process | System V | POSIX |
parent |
|
|
child |
|
|
Message Queues
process | System V | POSIX |
parent |
|
|
child |
|
|
Makefile