Part ofSystems Programming Companion, week 9
Process Management
Processes are Unix's basic unit of isolation. Each one gets its own virtual address space, its own file descriptor table, its own execution state — a hermetic little world. Knowing how to spawn, manage, and coordinate them is bread-and-butter systems programming.
fork(): Creating a Child Process
fork() makes a new process by cloning the caller. The child comes out as a near-perfect duplicate of the parent:
#include <stdio.h>#include <unistd.h>#include <sys/wait.h>
int main() { pid_t pid = fork();
if (pid < 0) { perror("fork failed"); return 1; } else if (pid == 0) { // Child process printf("I am the child, PID %d\n", getpid()); } else { // Parent process printf("I am the parent, child PID is %d\n", pid); wait(NULL); // Wait for child to finish } return 0;}After fork():
- The parent receives the child's PID (a positive number)
- The child receives 0
- On error,
fork()returns -1
fork() leans on copy-on-write (COW). The child doesn't get a fresh physical copy of the parent's memory — both processes share the same pages until somebody writes one. At that moment the kernel copies just the modified page, leaving everything else shared. Even forking a process with a multi-gigabyte address space stays cheap, because only the page tables get copied up front.
exec(): Replacing the Process Image
fork() clones. exec() swaps your process out, replacing its image with a different program entirely:
#include <stdio.h>#include <unistd.h>#include <sys/wait.h>
int main() { pid_t pid = fork();
if (pid == 0) { // Child: replace with ls command execlp("ls", "ls", "-la", NULL); // If exec returns, it failed perror("exec failed"); _exit(1); } else { int status; waitpid(pid, &status, 0); if (WIFEXITED(status)) { printf("Child exited with status %d\n", WEXITSTATUS(status)); } } return 0;}The exec family comes in a confusing little zoo of variants:
| Function | Path | Args | Environment |
|---|---|---|---|
execl | Full path | List | Inherited |
execlp | PATH search | List | Inherited |
execle | Full path | List | Provided |
execv | Full path | Array | Inherited |
execvp | PATH search | Array | Inherited |
execve | Full path | Array | Provided |
waitpid(): Waiting for Children
waitpid blocks on a specific child (or any child, with -1) and pulls back its exit status:
pid_t pid = fork();if (pid == 0) { // Child work _exit(42);}
int status;waitpid(pid, &status, 0);
if (WIFEXITED(status)) { printf("Exited normally with code %d\n", WEXITSTATUS(status));} else if (WIFSIGNALED(status)) { printf("Killed by signal %d\n", WTERMSIG(status));}Pass WNOHANG and waitpid stops blocking. It returns straight away if no child has exited yet:
pid_t result = waitpid(-1, &status, WNOHANG);if (result > 0) { // A child exited} else if (result == 0) { // No child has exited yet}Pipes
A pipe wires one process's stdout to another's stdin:
#include <stdio.h>#include <unistd.h>#include <sys/wait.h>#include <string.h>
int main() { int pipefd[2]; pipe(pipefd); // pipefd[0] = read end, pipefd[1] = write end
pid_t pid = fork(); if (pid == 0) { // Child: read from pipe close(pipefd[1]); char buffer[256]; ssize_t n = read(pipefd[0], buffer, sizeof(buffer) - 1); if (n < 0) n = 0; // treat an error as "nothing read" buffer[n] = '\0'; printf("Child received: %s\n", buffer); close(pipefd[0]); _exit(0); } else { // Parent: write to pipe close(pipefd[0]); const char *msg = "Hello from parent!"; write(pipefd[1], msg, strlen(msg)); close(pipefd[1]); wait(NULL); } return 0;}dup2: Redirecting File Descriptors
dup2 is what makes shell-style redirection and pipelines possible. It overwrites one file descriptor with a copy of another:
#include <fcntl.h> // open() and the O_* flags
// Redirect stdout to a fileint fd = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);dup2(fd, STDOUT_FILENO);close(fd);printf("This goes to output.txt\n");Building a Pipeline
Stitch pipes, fork, exec, and dup2 together and you've got the makings of a shell pipeline like ls | grep .c | wc -l:
#include <stdio.h>#include <unistd.h>#include <sys/wait.h>
int main() { int pipe1[2], pipe2[2]; pipe(pipe1); pipe(pipe2);
// First child: ls if (fork() == 0) { dup2(pipe1[1], STDOUT_FILENO); close(pipe1[0]); close(pipe1[1]); close(pipe2[0]); close(pipe2[1]); execlp("ls", "ls", NULL); _exit(1); }
// Second child: grep .c if (fork() == 0) { dup2(pipe1[0], STDIN_FILENO); dup2(pipe2[1], STDOUT_FILENO); close(pipe1[0]); close(pipe1[1]); close(pipe2[0]); close(pipe2[1]); execlp("grep", "grep", ".c", NULL); _exit(1); }
// Third child: wc -l if (fork() == 0) { dup2(pipe2[0], STDIN_FILENO); close(pipe1[0]); close(pipe1[1]); close(pipe2[0]); close(pipe2[1]); execlp("wc", "wc", "-l", NULL); _exit(1); }
// Parent: close all pipe ends and wait close(pipe1[0]); close(pipe1[1]); close(pipe2[0]); close(pipe2[1]); wait(NULL); wait(NULL); wait(NULL); return 0;}Always close pipe ends you aren't using. Leave any process holding the write end open and the reader will hang waiting for EOF that never comes. This is the bug everyone writes the first time they build a pipeline.
With stdin, stdout and stderr already open, the two pipe() calls get fds 3 and 4 (pipe1) and 5 and 6 (pipe2). Straight after fork, every child holds all four. Once each child has run its dup2s and closed 3 to 6, and the parent has closed its copies too, only these wires remain:
Each pipe now has exactly one writer. When ls exits, pipe1's last write end closes and grep sees EOF; when grep exits, the same happens for wc. Skip one close(pipe1[1]) anywhere, the parent included, and grep waits forever.
Daemon Processes
A daemon is a background process that no longer has a controlling terminal. The classic incantation: double-fork.
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>#include <sys/stat.h>
void daemonize(void) { pid_t pid = fork(); if (pid < 0) exit(1); if (pid > 0) exit(0); // Parent exits
setsid(); // New session, no controlling terminal
pid = fork(); // Second fork prevents reacquiring a terminal if (pid < 0) exit(1); if (pid > 0) exit(0);
umask(0); chdir("/");
// Point stdin, stdout and stderr at /dev/null int fd = open("/dev/null", O_RDWR); if (fd < 0) exit(1); dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) close(fd);}
int main() { daemonize(); // Now running as a daemon while (1) { // Do background work sleep(60); } return 0;}Forking twice makes it impossible for the daemon to grab a controlling terminal by accident. setsid() opens a new session and makes the process the session leader.
Why redirect to /dev/null instead of simply closing descriptors 0, 1 and 2? Because open() always returns the lowest free descriptor. Close all three and the daemon's next open(), say of its database file, gets descriptor 1. From then on every stray printf and every library warning lands in the middle of your data. Pinning 0 to 2 to /dev/null keeps them occupied, and anything written there disappears harmlessly.
All this ceremony is for the classic SysV-style daemon. Under systemd, and in containers, you mostly shouldn't do any of it: run in the foreground, write logs to stdout or stderr, and let the service manager handle the session, the restarts and the log collection.
Process Groups and Job Control
Every process belongs to a process group. The shell hands each command or pipeline its own group. Signals aimed at a group land on every process inside it:
// Send SIGTERM to all processes in group 1234kill(-1234, SIGTERM);
// Set the process group of the current processsetpgid(0, 0); // Creates a new group with this process as leaderThat's the mechanic behind shell job control: Ctrl+C fires SIGINT at the whole foreground process group, not just one process.
Get processes, pipes, and signals straight in your head and you've got the toolkit for any Unix utility — small one-liners up through orchestration systems with moving parts everywhere. The capstone for this module pulls all three threads together into a working shell.
Challenges
Use fork() to create a child process. The child should print 'child' and the parent should wait for the child, then print 'parent'.