Processes: fork, exec & Pipes in C
Unix programs create processes with fork() (cloning into parent/child distinguished by return value: child gets 0, parent gets the pid) and replace programs with exec-family calls (execlp("ls", "ls", NULL) — same process, new code). Parents reap children with wait() to avoid zombies; pipe() plus dup2() wires stdout-to-stdin chains — the shell's | operator, built by hand.
File descriptors are the currency: 0/1/2 for stdio, close-on-exec flags for hygiene, and careful closing of unused pipe ends (or readers never see EOF). These five calls underpin every shell, server supervisor, and build tool on Unix.
fork clones
pid_t p = fork(); — 0 in the child, positive pid in the parent, -1 on failure. Both continue after the call.
exec replaces
execlp("ls", "ls", (char *)NULL); overlays new code — success never returns; failure returns -1 to handle.
wait reaps
wait(NULL) blocks until a child exits, collecting its status — unreaped children linger as zombies.
Pipes connect
pipe(fd) yields read/write ends; dup2(fd[1], 1) redirects stdout into the pipe — close unused ends so EOF propagates.
#include <stdio.h>#include <unistd.h>#include <sys/wait.h> int main(void) { pid_t p = fork(); if (p == 0) { execlp("echo", "echo", "child", (char *)NULL); _exit(1); } int status = 0; wait(&status); printf("reaped\n"); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.