Process Management and IPC
Open in the Padhaiko app2.1 Process creation and control (Fork, exec, wait)
A process is an active instance of a computer program in execution. Unlike a passive executable file stored on disk, a process owns live kernel resources tracked in a Process Control Block (PCB) (task_struct on Linux): a unique Process ID (PID), Parent PID (PPID), virtual address space (text, initialized data, BSS, heap, stack), CPU register state, signal mask, and an open File Descriptor Table.
Creating Processes with fork()
POSIX fork() System Call
pid_t fork(void); creates a new child process by duplicating the calling parent process. It is called once in the parent, yet returns twice:
- In the parent process,
fork()returns the positive PID of the newly created child. - In the child process,
fork()returns0. - On failure (e.g., process limit
RLIMIT_NPROCor out of memory),fork()returns-1in the parent and no child is created.
Modern Linux implements fork() using Copy-on-Write (CoW): the kernel does not immediately duplicate every physical RAM page of the parent. Instead, both parent and child share the same physical pages marked read-only; only when either process attempts to modify a page does the MMU trigger a fault so the kernel copies just that 4 KB page.
- Inherited by Child: Copy of memory segments, open file descriptors (sharing the same Open File Table entries and offsets), working directory, environment variables, signal handlers/masks, and UID/GID.
- Unique to Child: New PID, new PPID, reset CPU usage timers, and cleared pending signals/file locks.
Replacing a Process Image with the exec Family
While fork() clones the current program, the exec family replaces the calling process's virtual memory image (text, data, heap, stack) with a brand-new program loaded from disk. The PID remains unchanged, and on success exec*() never returns.
| Function | Argument Passing | Path Resolution | Environment |
|---|---|---|---|
execl(path, arg0, ..., NULL) | List (l) of const char * arguments | Exact file path | Inherits environ |
execlp(file, arg0, ..., NULL) | List (l) | Searches PATH (p) | Inherits environ |
execv(path, argv) | Vector/array (v) char *const argv[] | Exact file path | Inherits environ |
execvp(file, argv) | Vector/array (v) | Searches PATH (p) | Inherits environ |
execve(path, argv, envp) | Vector/array (v) — underlying Linux syscall | Exact file path | Explicit envp (e) |
Waiting for Children: wait(), waitpid(), Zombies, and Orphans
When a child terminates via exit(code) or _exit(code), the kernel frees its user memory and open fds, but retains its PCB entry (containing PID, exit code, and resource stats) until the parent collects it.
Zombie and Orphan Processes
- Zombie Process (
Zstate): A child that has already terminated, but whose parent has not yet calledwait()orwaitpid()to read its exit status. Too many zombies exhaust the system PID table. - Orphan Process: A child that is still running after its parent has terminated. The kernel immediately re-parents the orphan to PID 1 (
init/systemd, or a designated subreaper), which automatically callswait()when the orphan finishes.
pid_t wait(int *wstatus);blocks until any child terminates and returns its PID.pid_t waitpid(pid_t pid, int *wstatus, int options);waits for a specific child (pid > 0) or any child (pid == -1). PassingWNOHANGinoptionsmakeswaitpid()non-blocking (returns0immediately if no child has exited yet).- Status Inspection Macros:
WIFEXITED(status)checks normal exit andWEXITSTATUS(status)extracts the 8-bit exit code (0–255);WIFSIGNALED(status)checks signal termination andWTERMSIG(status)extracts the fatal signal number.
2.2 Process states and scheduling concepts
Because a CPU core can execute instructions for only one thread/process at a given instant, the operating system scheduler multiplexes CPU time across all ready processes through well-defined process states.
admitted dispatched (scheduled)
[ NEW ] -----------------> [ READY ] ------------------------> [ RUNNING ]
^ | |
| time quantum expired (preempt) | | exit()
+----------------------------------+ v
| [ ZOMBIE / ]
I/O or event | [TERMINATED]
completed | wait for I/O, sleep, or
[ BLOCKED / WAITING ] <-----------------+Linux Process States (visible in ps / top)
| Code | State Name | Meaning |
|---|---|---|
R | Running / Runnable | Currently executing on a CPU core or sitting in the run queue ready to run |
S | Interruptible Sleep | Waiting for an event (socket data, pipe, sleep(), wait()); wakes on signal |
D | Uninterruptible Sleep | Waiting directly on hardware/disk I/O; ignores signals until I/O finishes |
T | Stopped | Suspended by job control (SIGSTOP / SIGTSTP) or debugger trace (ptrace) |
Z | Zombie | Terminated execution, awaiting parent's wait() / waitpid() call |
Context Switching and Scheduling Metrics
A context switch saves the outgoing process's CPU registers, program counter, stack pointer, and memory mapping into its PCB, loads the incoming process's state and page-table base register, and resumes execution. Context switches are pure overhead (typically a few microseconds plus cold TLB/cache misses).
- Non-preemptive vs. Preemptive Scheduling: Non-preemptive schedulers hold the CPU until the process blocks or exits; preemptive schedulers use hardware timer interrupts to forcibly switch processes after a time quantum (time slice).
- Core Scheduling Algorithms:
- FCFS (First-Come, First-Served): FIFO queue; simple, non-preemptive, suffers from the convoy effect.
- SJF / SRTF (Shortest Job / Remaining Time First): Minimizes average waiting time, but can starve long processes and requires predicting CPU burst lengths.
- Priority Scheduling: Runs highest-priority ready process first; requires aging to prevent starvation.
- Round Robin (RR): Preemptive FCFS with fixed time quantum
q. Smallqimproves interactive response time at higher context-switch overhead; largeqdegrades toward FCFS. - Linux CFS (Completely Fair Scheduler): Tracks each runnable task's virtual runtime (
vruntime) (weighted bynicepriority) in a red-black tree and always picks the task with the smallestvruntime(replaced in recent kernels by EEVDF, which preserves virtual-time fairness with explicit latency targets).
| Metric | Formula | Goal |
|---|---|---|
| Turnaround Time (TAT) | Completion Time - Arrival Time | Minimize |
| Waiting Time (WT) | Turnaround Time - Total CPU Burst Time | Minimize |
| Response Time (RT) | First CPU Dispatch Time - Arrival Time | Minimize (interactive apps) |
| Throughput | Number of Completed Processes / Total Time | Maximize |
2.3 Signals and signal handling
A signal is a lightweight software interrupt delivered asynchronously to a process by the kernel, another process (kill(pid, sig)), or the process itself (raise(sig) / alarm(sec)) to notify it of an event.
| Signal | Default Action | Trigger / Typical Role |
|---|---|---|
SIGINT | Terminate | Terminal interrupt (Ctrl+C); graceful shutdown trigger |
SIGTERM | Terminate | Polite termination request (kill <pid>); catchable for cleanup |
SIGKILL | Terminate (forced) | Immediate termination; cannot be caught, blocked, or ignored |
SIGSTOP | Stop process | Suspends execution; cannot be caught, blocked, or ignored |
SIGCHLD | Ignore | Sent to parent when a child terminates or stops; used to reap zombies |
SIGPIPE | Terminate | Writing to a pipe or socket whose read end is already closed (servers often set SIG_IGN so write() returns -1 with EPIPE instead of crashing the server!) |
SIGHUP | Terminate | Controlling terminal closed; daemons catch it to reload configuration |
SIGALRM | Terminate | Timer expiration from alarm() or setitimer() (I/O timeouts) |
SIGSEGV | Terminate + core | Invalid memory reference (segmentation fault) |
Reliable Signal Handling with sigaction()
The legacy signal() call has inconsistent reset semantics across Unix systems. Production POSIX code always uses sigaction():
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
static void sigchld_handler(int sig) {
(void)sig;
int saved_errno = errno; /* preserve errno across handler */
while (waitpid(-1, NULL, WNOHANG) > 0) {
/* reap all terminated children */
}
errno = saved_errno;
}
void install_handlers(void) {
struct sigaction sa;
sa.sa_handler = sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
sigaction(SIGCHLD, &sa, NULL);
}2.4 Inter-process communication: Pipes and FIFOs, message queues, shared memory, semaphores
Because each process has an isolated virtual address space, independent processes cannot directly read or write each other's variables. Inter-Process Communication (IPC) provides kernel-mediated channels and synchronization primitives.
| Aspect | Pipes and FIFOs | Shared Memory |
|---|---|---|
| Data Model | Unstructured byte stream (read/write) | Direct memory region mapped into both virtual spaces |
| Speed / Copies | Moderate (2 copies: user -> kernel -> user) | Fastest (zero kernel copies after setup) |
| Synchronization | Kernel blocks reader on empty, writer on full | None built-in; programmer must pair with semaphores/mutexes |
| Process Relation | Anonymous pipe: related; FIFO: any process | Any process knowing key or POSIX name (/my_shm) |
1. Pipes and FIFOs (Named Pipes)
- Anonymous Pipe (
pipe(int pfd[2])): Creates a unidirectional kernel buffer withpfd[0](read end) andpfd[1](write end). Typically created beforefork(). The writer closespfd[0]and the reader closespfd[1]. When all write ends close,read()sees0(EOF); if all read ends close,write()triggersSIGPIPE/EPIPE. - FIFO / Named Pipe (
mkfifo("/tmp/myfifo", 0666)): Creates a persistent named node in the filesystem. Any two unrelated processes can open it withopen()for byte-stream communication (by defaultopen()blocks until both a reader and writer have opened the FIFO).
2. Message Queues
- POSIX (
mq_open,mq_send,mq_receive) and System V (msgget,msgsnd,msgrcv): Unlike pipes, message queues preserve discrete message boundaries and attach an integer priority / type to each message so high-priority messages can be dequeued ahead of older low-priority messages.
3. Shared Memory
- POSIX (
shm_open->ftruncate->mmap) and System V (shmget->shmat): Maps the exact same physical RAM frames into the virtual address spaces of multiple processes. Once mapped, writing to a pointer in Process A is immediately visible in Process B without a single system call. Because concurrent access causes race conditions, shared memory is almost always paired with semaphores.
4. Semaphores
Semaphore Operations (wait and post)
A semaphore is an integer synchronization counter managed atomically via two operations:
sem_wait()(DijkstraP()/ down): If value > 0, decrements it and proceeds; if value == 0, blocks the process/thread until another entity posts.sem_post()(DijkstraV()/ up): Atomically increments the counter and wakes a waiting process/thread if any are blocked.
- Binary Semaphore (initial value
1): Acts as a mutual exclusion lock (mutex) guarding a critical section in shared memory. - Counting Semaphore (initial value
N): Tracks available slots or items in a bounded producer-consumer ring buffer (empty = N,full = 0,mutex = 1). - POSIX Variants: Named semaphores (
sem_open("/name", ...)) work easily across unrelated processes; unnamed semaphores (sem_init(&sem, pshared=1, val)) live directly inside shared memory.
| IPC Mechanism | Message Boundaries? | Built-in Sync? | Unrelated Processes? | Best Use Case |
|---|---|---|---|---|
| Anonymous Pipe | No (byte stream) | Yes (blocking I/O) | No (parent-child) | Shell pipelines between parent and child commands |
| FIFO (Named Pipe) | No (byte stream) | Yes (blocking I/O) | Yes | Simple local client-server byte streaming |
| Message Queue | Yes | Yes | Yes | Prioritized commands, structured discrete messages |
| Shared Memory | N/A (raw RAM) | No (use semaphore) | Yes | High-throughput video/IPC buffers, low-latency trading |
| Semaphore | N/A (counter only) | Is a sync tool | Yes | Guarding shared memory and producer-consumer bounds |
Worked Examples
Fork Process Tree and Parent-Child Pipe Communication
- Consider a C program that executes three consecutive unconditional
fork()calls (fork(); fork(); fork();) with no errors. How many total processes exist at the end, and how many new child processes were created? - Write a C program where a parent creates an anonymous pipe, forks a child, writes
"NET-SYS"into the pipe, and the child reads and prints it before exiting with status42.
Counting Processes Created by Consecutive fork() Calls:
- Before any
fork():1process. - After 1st
fork():2processes. - After 2nd
fork():4processes. - After 3rd
fork():2^3 = 8total processes (1original parent +7newly created descendant processes).
Implementing the Pipe + fork() + waitpid() C Program: Remember to close unused pipe ends (pfd[0] in parent, pfd[1] in child) so the reader cleanly sees EOF once the parent closes pfd[1].
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int pfd[2];
if (pipe(pfd) < 0) { perror("pipe"); return 1; }
pid_t pid = fork();
if (pid < 0) { perror("fork"); return 1; }
if (pid == 0) {
close(pfd[1]); /* child closes unused write end */
char buf[64];
ssize_t n = read(pfd[0], buf, sizeof(buf) - 1);
if (n > 0) {
buf[n] = '\0';
printf("Child received: %s\n", buf);
}
close(pfd[0]);
exit(42);
} else {
close(pfd[0]); /* parent closes unused read end */
const char *msg = "NET-SYS";
write(pfd[1], msg, strlen(msg));
close(pfd[1]); /* signals EOF to child */
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("Child exited with code %d\n", WEXITSTATUS(status));
}
}
return 0;
}- Three consecutive unconditional
fork()calls yield8total processes (7new children). - The parent writes
"NET-SYS"topfd[1], closes it to trigger EOF, and collects the child's exit code42usingwaitpid()andWEXITSTATUS(status).
Round-Robin (q = 4 ms) CPU Scheduling Calculation
Four processes arrive at the ready queue with the arrival and CPU burst times below. Compute the Turnaround Time (TAT) and Waiting Time (WT) for each process, and find the average TAT and average WT under Round-Robin (RR) scheduling with time quantum q = 4 ms:
| Process | Arrival Time (ms) | Burst Time (ms) |
|---|---|---|
| P1 | 0 | 6 |
| P2 | 1 | 8 |
| P3 | 2 | 3 |
| P4 | 4 | 4 |
Tracing the Ready Queue and Gantt Execution (q = 4 ms):
t = 0: P1 arrives -> Queue[P1]. P1 runs0..4(remaining:P1=2). During0..4, P2 (t=1), P3 (t=2), and P4 (t=4) arrive. Queue becomes[P2, P3, P4, P1].t = 4: P2 runs4..8(remaining:P2=4). Queue becomes[P3, P4, P1, P2].t = 8: P3 runs8..11(burst3 <= 4, finishes at11-> Wait: let's re-check order att=4!).
Let's trace carefully: at t = 4, P1 is preempted right as P4 arrives (t=4): standard convention places newly arrived P4 before preempted P1 ([P2, P3, P4, P1]). Let's verify completion times!
0..4: P1 (rem 2); arrivals: P2(1), P3(2), P4(4) -> queue:[P2, P3, P4, P1]4..8: P2 (rem 4) -> queue:[P3, P4, P1, P2]8..11: P3 finishes at11! -> queue:[P4, P1, P2]11..15: P4 finishes at15! -> queue:[P1, P2]15..17: P1 finishes at17! -> queue:[P2]17..21: P2 finishes at21!
Wait: let's match our @verify numbers or update @verify to match these exact completion times! Let's check:
- P1: Arrival
0, Burst6, Completion17->TAT = 17 - 0 = 17,WT = 17 - 6 = 11 - P2: Arrival
1, Burst8, Completion21->TAT = 21 - 1 = 20,WT = 20 - 8 = 12 - P3: Arrival
2, Burst3, Completion11->TAT = 11 - 2 = 9,WT = 9 - 3 = 6 - P4: Arrival
4, Burst4, Completion15->TAT = 15 - 4 = 11,WT = 11 - 4 = 7
Average TAT = (17 + 20 + 9 + 11) / 4 = 57 / 4 = 14.25 ms Average WT = (11 + 12 + 6 + 7) / 4 = 36 / 4 = 9.00 ms Let's update @verify to (17 + 20 + 9 + 11) / 4 == 14.25 and (11 + 12 + 6 + 7) / 4 == 9.0!
Summary Gantt and Metrics Table:
| Process | Arrival | Burst | Completion | Turnaround (C - A) | Waiting (TAT - B) |
|---|---|---|---|---|---|
| P1 | 0 | 6 | 17 | 17 | 11 |
| P2 | 1 | 8 | 21 | 20 | 12 |
| P3 | 2 | 3 | 11 | 9 | 6 |
| P4 | 4 | 4 | 15 | 11 | 7 |
- Average TAT =
(17 + 20 + 9 + 11) / 4 = 57 / 4 = 14.25 ms - Average WT =
(11 + 12 + 6 + 7) / 4 = 36 / 4 = 9.00 ms
Gantt timeline: P1(0-4) -> P2(4-8) -> P3(8-11) -> P4(11-15) -> P1(15-17) -> P2(17-21). Average Turnaround Time = 14.25 ms, Average Waiting Time = 9.00 ms.
POSIX Shared Memory Producer-Consumer Synchronization with Semaphores
Write a C snippet showing how two unrelated processes (a writer and a reader) attach a 4096-byte POSIX shared memory segment (/net_buf) and coordinate access without race conditions using a POSIX named semaphore (/net_sem).
Writer Process (Creates Shared Memory + Binary Semaphore):
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void) {
int fd = shm_open("/net_buf", O_CREAT | O_RDWR, 0666);
ftruncate(fd, 4096);
char *ptr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
sem_t *sem = sem_open("/net_sem", O_CREAT, 0666, 0); /* initially 0 (empty) */
snprintf(ptr, 4096, "Packet #101: 200 OK");
sem_post(sem); /* notify reader that data is ready */
munmap(ptr, 4096);
close(fd);
sem_close(sem);
return 0;
}Reader Process (Waits on Semaphore, Reads Memory, Cleans Up):
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void) {
int fd = shm_open("/net_buf", O_RDONLY, 0666);
char *ptr = mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0);
sem_t *sem = sem_open("/net_sem", 0);
sem_wait(sem); /* blocks until writer calls sem_post() */
printf("Reader read: %s\n", ptr);
munmap(ptr, 4096);
close(fd);
shm_unlink("/net_buf");
sem_close(sem);
sem_unlink("/net_sem");
return 0;
}shm_open() + ftruncate() + mmap(MAP_SHARED) maps identical physical RAM pages into both processes, while the POSIX semaphore initialized to 0 ensures the reader blocks inside sem_wait() until the writer writes the payload and calls sem_post().
Exercises
Practice Exercises — Process Management and IPC
- A C program runs:
if (fork() == 0) {
fork();
}How many total processes are running after this code completes?
- Later, a parent calls
waitpid(pid, &status, 0)and observes rawstatus = 0x1A00(assuming standard Linux wait-status encoding where low 7 bits = signal number0and bits 8–15 = exit code). Did the child exit normally, and what was its decimal exit status code?
Part 1 — Counting Processes:
- Initially
1parent process runs the outerfork(), creating1child (C1). Now2processes exist: parent (P) and child (C1). - In
P, the outerfork()returnedC1's PID (!= 0), soPskips theifbody. - In
C1, the outerfork()returned0, soC1executes the innerfork(), creating1grandchild (GC1). - Total processes =
P + C1 + GC1? Wait:1 + 1 + 1 = 3processes!
Let's check carefully:
- Initially:
{P}(1 process) - Outer
fork():PcreatesC1.{P, C1}(2 processes) Pgetsfork() > 0-> skips innerfork().C1getsfork() == 0-> runs innerfork(), creatingGC1.{P, C1, GC1}-> 3 total processes (2new children)!
(Wait: let's fix @verify from 1 + 1 + 2 == 4 to 1 + 1 + 1 == 3!)
Part 2 — Decoding status = 0x1A00: In Linux waitpid() status encoding:
- Low 7 bits (
status & 0x7F) =0x1A00 & 0x7F = 0, meaningWIFEXITED(status)is true (normal exit, not killed by a signal). - Bits 8–15 (
(status >> 8) & 0xFF) =0x1A=1 * 16 + 10 = 26, soWEXITSTATUS(status) = 26.
- 3 total processes (
1original parent +1child +1grandchild). - Yes, the child exited normally (
WIFEXITEDis true) with decimal exit code 26.
Three processes arrive as shown below. Compute the average Turnaround Time and average Waiting Time using Preemptive Shortest Remaining Time First (SRTF) scheduling:
| Process | Arrival Time (ms) | Burst Time (ms) |
|---|---|---|
| P1 | 0 | 5 |
| P2 | 1 | 6 |
| P3 | 1 | 3 |
Tracing SRTF Timeline:
t = 0..1: Only P1 has arrived -> P1 runs for1 ms(remaining:P1=4).t = 1: P2 (rem=6) and P3 (rem=3) arrive. SinceP3 (3) < P1 (4) < P2 (6), P3 preempts P1!t = 1..4: P3 runs to completion att = 4(TAT = 4 - 1 = 3,WT = 3 - 3 = 0).t = 4..8: Remaining areP1 (4)andP2 (6). P1 runs to completion att = 8(TAT = 8 - 0 = 8,WT = 8 - 5 = 3).t = 8..14: P2 runs to completion att = 14(TAT = 14 - 1 = 13,WT = 13 - 6 = 7).
Wait: let's double check! P1: C=8, TAT=8, WT=3; P2: C=14, TAT=13, WT=7; P3: C=4, TAT=3, WT=0. Avg TAT = (8 + 13 + 3) / 3 = 24 / 3 = 8.0 ms. Avg WT = (3 + 7 + 0) / 3 = 10 / 3 = 3.33 ms. Let's make sure @verify checks (8 + 13 + 3) / 3 == 8.0 and (3 + 7 + 0) / 3! (Let's fix @verify in q02 right away!)
Computed Metrics:
P1: Completion8, TAT8 - 0 = 8 ms, WT8 - 5 = 3 msP2: Completion14, TAT14 - 1 = 13 ms, WT13 - 6 = 7 msP3: Completion4, TAT4 - 1 = 3 ms, WT3 - 3 = 0 ms- Average TAT =
(8 + 13 + 3) / 3 = 8.00 ms; Average WT =(3 + 7 + 0) / 3 = 3.33 ms.
Gantt timeline: P1(0-1) -> P3(1-4) -> P1(4-8) -> P2(8-14). Average Turnaround Time = 8.00 ms; Average Waiting Time = 3.33 ms.
Distinguish between a zombie process and an orphan process. Why must a multi-process network server use while (waitpid(-1, NULL, WNOHANG) > 0) inside its SIGCHLD handler instead of a single wait(NULL) call, and why should network servers ignore SIGPIPE?
Zombie vs. Orphan:
- A zombie is a dead child whose exit status has not yet been reaped by its still-running parent via
wait()/waitpid(). - An orphan is a live child whose parent has died; PID 1 (
init/systemd) adopts and eventually reaps it automatically.
Why SIGCHLD Needs a WNOHANG Loop & Why Ignore SIGPIPE:
- Standard signals are not queued: If three child worker processes exit at nearly the same moment while
SIGCHLDis being handled, the kernel coalesces them into a singleSIGCHLDdelivery. Callingwait(NULL)once would reap only one child and leave two zombies behind; looping withWNOHANGreaps every exited child without blocking the parent when no more exited children remain. - Ignoring
SIGPIPE: When a remote client abruptly closes its TCP socket and the server callswrite()/send()on that socket, the kernel raisesSIGPIPE, whose default action kills the entire server process. Settingsignal(SIGPIPE, SIG_IGN)(orsigaction) makeswrite()simply return-1witherrno = EPIPE, letting the server close that single client cleanly.
Zombies are terminated children awaiting wait(); orphans are live children whose parent exited (adopted by PID 1). Because standard signals coalesce rather than queue, SIGCHLD must loop with waitpid(-1, NULL, WNOHANG) to reap all exited children without blocking. Network servers ignore SIGPIPE so writing to a disconnected client returns EPIPE instead of terminating the whole server.
Compare Pipes, FIFOs, Message Queues, and Shared Memory across four dimensions: (a) process relationship requirement, (b) message boundary preservation, (c) built-in synchronization, and (d) data-copy overhead.
Comparison Across the Four Dimensions:
- Anonymous Pipes: (a) Related processes only (
fork()), (b) No boundaries (byte stream), (c) Built-in kernel blocking synchronization, (d) 2 copies (user -> kernel -> user). - FIFOs (Named Pipes): (a) Unrelated processes (via filesystem path), (b) No boundaries (byte stream), (c) Built-in kernel blocking synchronization, (d) 2 copies (user -> kernel -> user).
- Message Queues (POSIX/SysV): (a) Unrelated processes (by name/key), (b) Preserves discrete message boundaries with priority, (c) Built-in blocking/non-blocking queue sync, (d) 2 copies (user -> kernel -> user).
- Shared Memory: (a) Unrelated processes (by name/key), (b) No message structure (raw shared RAM), (c) No built-in sync (must pair with semaphores/mutexes), (d) Zero copies after
mmap/shmat.
Pipes (related only) and FIFOs (unrelated) are byte streams with kernel sync and 2 copies. Message queues support unrelated processes with discrete prioritized messages and kernel sync (2 copies). Shared memory supports unrelated processes with zero-copy speed, but requires external synchronization via semaphores.
A shared-memory circular ring buffer has 8 slots, each holding a 4096-byte packet buffer, guarded by three POSIX semaphores (empty, full, mutex).
- State the exact initial integer values for
empty,full, andmutex, and calculate the total shared memory size in bytes. - If a producer transfers 32 KiB using a 64-byte anonymous pipe write loop per message, how many pipe writes are needed? Why would a 64-KiB single atomic
write()onto a 4096-byte-buffer pipe block or fail compared to shared memory?
Part 1 — Semaphore Initial Values and Shared Memory Size:
- Initial values:
empty = 8(all 8 slots free),full = 0(no filled slots yet),mutex = 1(binary mutex unlocked). - Shared memory size =
8 * 4096 = 32,768 bytes(32 KiB).
Part 2 — Pipe Writes & PIPE_BUF Atomicity:
- Number of 64-byte pipe writes for 32 KiB (
32,768 bytes) =32,768 / 64 = 512writes. - POSIX guarantees atomic, non-interleaved pipe writes only up to
PIPE_BUF(typically 4096 bytes on Linux). A 64-KiB write exceeds both the 4096-byte atomicity guarantee (risking interleaved bytes from concurrent writers) and may block repeatedly until the reader drains the kernel pipe buffer—whereas shared memory lets the producer write directly into its reserved 4096-byte slot with zero kernel copies oncesem_wait(&empty)succeeds.
empty = 8,full = 0,mutex = 1; total buffer = 32,768 bytes (32 KiB).- 512 writes are required. Writes larger than
PIPE_BUF(4096 bytes) lose POSIX atomicity and block until the reader drains the pipe buffer, whereas shared memory transfers data directly in RAM with zero kernel copies.