linux-sysprog · advanced · ~35 min
The mental model of pipe-chain plumbing.
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.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.
N >= 1.
Two arrays of length N.
No allocations; just fill the arrays.
void pipe_chain_plan(int n, int *read_for, int *write_for) { /* TODO */ }
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).
N == 1: process reads stdin, writes stdout.
O(N).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.