PadhaikoAll subjects

Process Management and IPC

Network and Systems Programming (ENCT 386)

Open in the Padhaiko app

2.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()

Definition

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:

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.

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.

POSIX exec Family Variants
FunctionArgument PassingPath ResolutionEnvironment
execl(path, arg0, ..., NULL)List (l) of const char * argumentsExact file pathInherits environ
execlp(file, arg0, ..., NULL)List (l)Searches PATH (p)Inherits environ
execv(path, argv)Vector/array (v) char *const argv[]Exact file pathInherits environ
execvp(file, argv)Vector/array (v)Searches PATH (p)Inherits environ
execve(path, argv, envp)Vector/array (v) — underlying Linux syscallExact file pathExplicit 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.

Definition

Zombie and Orphan Processes


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.

Process State Transition DiagramText
                  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)

Linux Kernel Process States
CodeState NameMeaning
RRunning / RunnableCurrently executing on a CPU core or sitting in the run queue ready to run
SInterruptible SleepWaiting for an event (socket data, pipe, sleep(), wait()); wakes on signal
DUninterruptible SleepWaiting directly on hardware/disk I/O; ignores signals until I/O finishes
TStoppedSuspended by job control (SIGSTOP / SIGTSTP) or debugger trace (ptrace)
ZZombieTerminated 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).

Standard Scheduling Evaluation Metrics
MetricFormulaGoal
Turnaround Time (TAT)Completion Time - Arrival TimeMinimize
Waiting Time (WT)Turnaround Time - Total CPU Burst TimeMinimize
Response Time (RT)First CPU Dispatch Time - Arrival TimeMinimize (interactive apps)
ThroughputNumber of Completed Processes / Total TimeMaximize

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.

Common POSIX Signals in Network and Systems Programming
SignalDefault ActionTrigger / Typical Role
SIGINTTerminateTerminal interrupt (Ctrl+C); graceful shutdown trigger
SIGTERMTerminatePolite termination request (kill <pid>); catchable for cleanup
SIGKILLTerminate (forced)Immediate termination; cannot be caught, blocked, or ignored
SIGSTOPStop processSuspends execution; cannot be caught, blocked, or ignored
SIGCHLDIgnoreSent to parent when a child terminates or stops; used to reap zombies
SIGPIPETerminateWriting 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!)
SIGHUPTerminateControlling terminal closed; daemons catch it to reload configuration
SIGALRMTerminateTimer expiration from alarm() or setitimer() (I/O timeouts)
SIGSEGVTerminate + coreInvalid 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():

Setting a Reliable SIGCHLD Handler with sigaction()C
#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.

AspectPipes and FIFOsShared Memory
Data ModelUnstructured byte stream (read/write)Direct memory region mapped into both virtual spaces
Speed / CopiesModerate (2 copies: user -> kernel -> user)Fastest (zero kernel copies after setup)
SynchronizationKernel blocks reader on empty, writer on fullNone built-in; programmer must pair with semaphores/mutexes
Process RelationAnonymous pipe: related; FIFO: any processAny process knowing key or POSIX name (/my_shm)

1. Pipes and FIFOs (Named Pipes)

2. Message Queues

3. Shared Memory

4. Semaphores

Definition

Semaphore Operations (wait and post)

A semaphore is an integer synchronization counter managed atomically via two operations:

Summary Comparison of Linux IPC Mechanisms
IPC MechanismMessage Boundaries?Built-in Sync?Unrelated Processes?Best Use Case
Anonymous PipeNo (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)YesSimple local client-server byte streaming
Message QueueYesYesYesPrioritized commands, structured discrete messages
Shared MemoryN/A (raw RAM)No (use semaphore)YesHigh-throughput video/IPC buffers, low-latency trading
SemaphoreN/A (counter only)Is a sync toolYesGuarding shared memory and producer-consumer bounds

Worked Examples

Example

Fork Process Tree and Parent-Child Pipe Communication

  1. 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?
  2. 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 status 42.

Counting Processes Created by Consecutive fork() Calls:

  • Before any fork(): 1 process.
  • After 1st fork(): 2 processes.
  • After 2nd fork(): 4 processes.
  • After 3rd fork(): 2^3 = 8 total processes (1 original parent + 7 newly 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].

Parent-to-Child Pipe Communication with Exit Status CheckC
#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;
}
Answer:
  1. Three consecutive unconditional fork() calls yield 8 total processes (7 new children).
  2. The parent writes "NET-SYS" to pfd[1], closes it to trigger EOF, and collects the child's exit code 42 using waitpid() and WEXITSTATUS(status).
Example

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 and Burst Times
ProcessArrival Time (ms)Burst Time (ms)
P106
P218
P323
P444

Tracing the Ready Queue and Gantt Execution (q = 4 ms):

  • t = 0: P1 arrives -> Queue [P1]. P1 runs 0..4 (remaining: P1=2). During 0..4, P2 (t=1), P3 (t=2), and P4 (t=4) arrive. Queue becomes [P2, P3, P4, P1].
  • t = 4: P2 runs 4..8 (remaining: P2=4). Queue becomes [P3, P4, P1, P2].
  • t = 8: P3 runs 8..11 (burst 3 <= 4, finishes at 11 -> Wait: let's re-check order at t=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 at 11! -> queue: [P4, P1, P2]
  • 11..15: P4 finishes at 15! -> queue: [P1, P2]
  • 15..17: P1 finishes at 17! -> queue: [P2]
  • 17..21: P2 finishes at 21!

Wait: let's match our @verify numbers or update @verify to match these exact completion times! Let's check:

  • P1: Arrival 0, Burst 6, Completion 17 -> TAT = 17 - 0 = 17, WT = 17 - 6 = 11
  • P2: Arrival 1, Burst 8, Completion 21 -> TAT = 21 - 1 = 20, WT = 20 - 8 = 12
  • P3: Arrival 2, Burst 3, Completion 11 -> TAT = 11 - 2 = 9, WT = 9 - 3 = 6
  • P4: Arrival 4, Burst 4, Completion 15 -> 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:

Round-Robin (q = 4 ms) Execution Results
ProcessArrivalBurstCompletionTurnaround (C - A)Waiting (TAT - B)
P106171711
P218212012
P3231196
P44415117
  • Average TAT = (17 + 20 + 9 + 11) / 4 = 57 / 4 = 14.25 ms
  • Average WT = (11 + 12 + 6 + 7) / 4 = 36 / 4 = 9.00 ms
Answer:

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.

Example

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):

POSIX Shared Memory and Semaphore WriterC
#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):

POSIX Shared Memory and Semaphore ReaderC
#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;
}
Answer:

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

Question 1
  1. A C program runs:
C
if (fork() == 0) {
    fork();
}

How many total processes are running after this code completes?

  1. Later, a parent calls waitpid(pid, &status, 0) and observes raw status = 0x1A00 (assuming standard Linux wait-status encoding where low 7 bits = signal number 0 and bits 8–15 = exit code). Did the child exit normally, and what was its decimal exit status code?

Part 1 — Counting Processes:

  • Initially 1 parent process runs the outer fork(), creating 1 child (C1). Now 2 processes exist: parent (P) and child (C1).
  • In P, the outer fork() returned C1's PID (!= 0), so P skips the if body.
  • In C1, the outer fork() returned 0, so C1 executes the inner fork(), creating 1 grandchild (GC1).
  • Total processes = P + C1 + GC1? Wait: 1 + 1 + 1 = 3 processes!

Let's check carefully:

  • Initially: {P} (1 process)
  • Outer fork(): P creates C1. {P, C1} (2 processes)
  • P gets fork() > 0 -> skips inner fork().
  • C1 gets fork() == 0 -> runs inner fork(), creating GC1. {P, C1, GC1} -> 3 total processes (2 new 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, meaning WIFEXITED(status) is true (normal exit, not killed by a signal).
  • Bits 8–15 ((status >> 8) & 0xFF) = 0x1A = 1 * 16 + 10 = 26, so WEXITSTATUS(status) = 26.
Answer:
  1. 3 total processes (1 original parent + 1 child + 1 grandchild).
  2. Yes, the child exited normally (WIFEXITED is true) with decimal exit code 26.
Question 2

Three processes arrive as shown below. Compute the average Turnaround Time and average Waiting Time using Preemptive Shortest Remaining Time First (SRTF) scheduling:

SRTF Scheduling Input
ProcessArrival Time (ms)Burst Time (ms)
P105
P216
P313

Tracing SRTF Timeline:

  • t = 0..1: Only P1 has arrived -> P1 runs for 1 ms (remaining: P1=4).
  • t = 1: P2 (rem=6) and P3 (rem=3) arrive. Since P3 (3) < P1 (4) < P2 (6), P3 preempts P1!
  • t = 1..4: P3 runs to completion at t = 4 (TAT = 4 - 1 = 3, WT = 3 - 3 = 0).
  • t = 4..8: Remaining are P1 (4) and P2 (6). P1 runs to completion at t = 8 (TAT = 8 - 0 = 8, WT = 8 - 5 = 3).
  • t = 8..14: P2 runs to completion at t = 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: Completion 8, TAT 8 - 0 = 8 ms, WT 8 - 5 = 3 ms
  • P2: Completion 14, TAT 14 - 1 = 13 ms, WT 13 - 6 = 7 ms
  • P3: Completion 4, TAT 4 - 1 = 3 ms, WT 3 - 3 = 0 ms
  • Average TAT = (8 + 13 + 3) / 3 = 8.00 ms; Average WT = (3 + 7 + 0) / 3 = 3.33 ms.
Answer:

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.

Question 3

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:

  1. Standard signals are not queued: If three child worker processes exit at nearly the same moment while SIGCHLD is being handled, the kernel coalesces them into a single SIGCHLD delivery. Calling wait(NULL) once would reap only one child and leave two zombies behind; looping with WNOHANG reaps every exited child without blocking the parent when no more exited children remain.
  2. Ignoring SIGPIPE: When a remote client abruptly closes its TCP socket and the server calls write()/send() on that socket, the kernel raises SIGPIPE, whose default action kills the entire server process. Setting signal(SIGPIPE, SIG_IGN) (or sigaction) makes write() simply return -1 with errno = EPIPE, letting the server close that single client cleanly.
Answer:

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.

Question 4

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.
Answer:

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.

Question 5

A shared-memory circular ring buffer has 8 slots, each holding a 4096-byte packet buffer, guarded by three POSIX semaphores (empty, full, mutex).

  1. State the exact initial integer values for empty, full, and mutex, and calculate the total shared memory size in bytes.
  2. 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 = 512 writes.
  • 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 once sem_wait(&empty) succeeds.
Answer:
  1. empty = 8, full = 0, mutex = 1; total buffer = 32,768 bytes (32 KiB).
  2. 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.
← System Programming FundamentalsThreads and Concurrent Programming →