linux-sysprog · advanced · ~35 min

Plan a pipe chain for N processes

The mental model of pipe-chain plumbing.

Challenge

For an N-process chain (p[0] | p[1] | ... | p[N-1]), compute the read/write file descriptors each process uses. For convenience, assume pipes are pre-created: pipe i has read end r[i] and write end w[i], with i in 0..N-2.

Implement void pipe_chain_plan(int n, int *read_for, int *write_for) where:

  • read_for[i] is the index of the pipe (r[]) that process i reads from, or -1 if it reads from stdin.
  • write_for[i] is the index of the pipe (w[]) that process i writes to, or -1 if it writes to stdout.

Why this matters

a | b | c in shell becomes a chain of pipes between N processes. Computing which fd each child reads from / writes to is non-obvious — getting it right matters because tip-1 left-open fd leaks an unkillable EOF.

Input format

N >= 1.

Output format

Two arrays of length N.

Constraints

No allocations; just fill the arrays.

Starter code

void pipe_chain_plan(int n, int *read_for, int *write_for) { /* TODO */ }

Common mistakes

Off-by-one (last process should write to stdout, not pipe N-1); reversing reader vs writer ends; using pipe i for both ends of two adjacent processes (instead of one end each).

Edge cases to handle

N == 1: process reads stdin, writes stdout.

Complexity

O(N).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.