Learn C
#include "systems/processes_pipes.h"

Processes: fork, exec & Pipes in C

#concept

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.

#how it works
1

fork clones

pid_t p = fork(); — 0 in the child, positive pid in the parent, -1 on failure. Both continue after the call.

2

exec replaces

execlp("ls", "ls", (char *)NULL); overlays new code — success never returns; failure returns -1 to handle.

3

wait reaps

wait(NULL) blocks until a child exits, collecting its status — unreaped children linger as zombies.

4

Pipes connect

pipe(fd) yields read/write ends; dup2(fd[1], 1) redirects stdout into the pipe — close unused ends so EOF propagates.

#example
#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;
}
Output
child
reaped
1fork splits execution — the child branch (p == 0) overlays echo via execlp.
2The child prints child through the new program image; _exit guards the impossible exec-failure path.
3The parent's wait collects the child (no zombie), then reaped prints — full lifecycle managed.
#use cases
Supervisors spawning and reaping worker processes
Shell-style pipelines built from pipe/fork/dup2/wait
Running helper programs with execlp and checked failures
Closing unused pipe ends so readers observe EOF correctly

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.