20. Inter-Process Communication
Prologue
- Pipes
- Use file descriptors
- Works across memory spaces
- Relies on inheritance of file descriptors → does not work for unrelated processes
- Named Pipes
- Uses file system as namespace for pipe
- Works for unrelated processes
- Carries the overhead of the file system
- IPC Objects
- Uses system-global integer keys to refer to objects
Message Queues
- Similar to FIFO, but with additional functionality such as being able to pull certain messages out of the queue before they reach the front. Thus, supporting priority.
- Multiple processes can read from or write into the same message queue - not possible in FIFO.
- MQ does not require the ends be simultaneously connected while FIFO does.
- MQ allows for asynchronous delivery of messages.
- A pipe is a byte stream between two processes, and streams have no concept of “packets”. e.g. If the producer sends data through multiple write() calls, it’s possible for the consumer to see it all in one read() call. Without special care, pipes can fail.
// returns the message queue ID on success.
int msgget(key_t key, int msgflg);
// generates a key.
key_t ftok(const char *path, int id);
// sends a message into the queue
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
// receive from a queue
int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
// destroy the queue
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
// shared memory segment
int shmid = shmget(key_t key, size_t size, int shmflg);
Shared Memory
- Shared memory files are special files that allow processes to quickly and directly share data
- Like pipes, the data isn’t stored persistently; it exists only in memory
- Unlike pipes, which are first-in-first-out streams, the shared memory space is accessible via random access
- Shared memory can be accessed with typical Unix I/O functions (read, write, lseek) or using mmap
- mmap makes a file’s contents directly accessible in memory instead of via read/write calls
21. Signals
- Think of signals as “software interrupts” from the kernel to the user program.
Conditions that generate signals
- Terminal-generated signals: triggered when the user presses a certain key on the terminal. (e.g. SIGINT and ^C).
- Hardware-exception generated signals: Hardware detects conditions and notifies kernel. (e.g. SIGFPE divided by 0, SIGSEGV invalid memory reference).