TIL: nix IPC APIs
2022-05-22 00:00:00 +0000 UTCThere are several different options for IPC on Unix systems. I read Beej’s Guide to Unix IPC as a high-level primer. Here are 4 options and some basic details of each.
- Pipes
- Pipes are used for one way communication.
- A call to
pipe(...)returns two file descriptors (one for writing, one for reading). - Since the “read” and “write” end are returned from the same function call, they are most appropriate for IPC within one program that calls
fork().
- FIFOs (named pipes)
- Like a pipe but named and on disc.
- Allows writing from one process and reading from another, unrelated process via disk.
- Interact with
open()like any other file.
- Message Queues
- One of the System V IPC interfaces. The others are shared memory segments and semaphore arrays. Visible via the
ipcscommand. - Like a FIFO, but supports typed messages. This allows you to skip messages, leaving them on the queue for someone else to consume. This allows simple bidirectional use.
- Requires generating an object of type
key_tusing ftok. This means each program interfacing with the queue must somehow synchronize their arguments toftok(...)in order to successfully communicate. - Takes messages in the form of a struct that looks like the definiton of
msgbufbelow. The first member of the struct must be of typelongbut the second can be anything. The size of the second member of the struct is passed to msgsnd as the argumentmsgsz.c struct msgbuf { long mtype; char mtext[1]; }
- One of the System V IPC interfaces. The others are shared memory segments and semaphore arrays. Visible via the
- Sockets
- The big guns in IPC. Provide an interface basically similar to network sockets but intended for IPC on the same system.
- Allow bidirectional communication.
- Support both TCP-like streaming mode and UDP-like datagram modes.
- Use the familiar
listen(...)andaccept(...)patterns.
Additional resources: The Linux Programmer’s Guide (1995).