Build a mini shell
Build a shell that runs commands with pipes, redirection, built-ins and background jobs.
By Invicly Tech, , in Linux System Programming. About 14 minutes to read.
In short
A shell is the perfect capstone for processes, file descriptors and signals. Yours reads a line, splits it into commands, sets up pipes and redirections with dup2, runs each command with fork and exec, and then waits or tracks background jobs. Built-ins like cd must run inside the shell itself, because a child cannot change its parent's directory.
Explained simply
A shell is a program that reads what you type and asks the kernel to run it. When you type ls -l, the shell does not know how to list files. It finds the program called ls, starts it as a new process, hands it the words ls and -l, and waits for it to finish.
Starting a program on Linux takes two steps. fork makes a copy of the shell. The copy, called the child, then calls exec, which replaces the copy with the new program. Between those two steps the child can still run shell code, and that is the moment to set up redirections and pipes.
Redirection and pipes work because programs read from file descriptor 0 (standard input) and write to file descriptor 1 (standard output) without caring what those really are. The shell quietly swaps them for a file or a pipe with dup2, and the program never notices.
A few commands, like cd and exit, cannot be separate programs. They must change the shell itself, so the shell runs them directly. Building your own small shell is the best way to see fork, exec, pipes and signals work together in one place.
Press Play on a diagram to walk through it one step at a time.
- 1Prompt and read a line
- 2Parse tokens, pipes and redirections
- 3Run a built-in or fork children
cd and exit run inside the shell.
- 4Wire pipes with dup2, then exec
Each child closes the pipe ends it does not use.
- 5Wait for the foreground job
Reap finished background jobs too.
- Back to step 1
- No fork at all
- Runs inside the shell process
- Can change the shell's state
- Must handle its own errors
- fork, then exec in the child
- Shell blocks in waitpid(pid)
- Gets Ctrl-C from the terminal
- Exit status shown to the user
- fork and exec, no waiting
- Prompt returns at once
- Reaped later after SIGCHLD
- Should not get Ctrl-C
- 1Terminal driver sees ^C
The kernel's tty layer, not the shell, reads it.
- 2SIGINT to foreground group
Every process in that group gets the signal.
- 3Shell ignores it
It set SIGINT to SIG_IGN at startup.
- 4Child dies
It restored SIG_DFL before exec.
- 5waitpid returns
WIFSIGNALED is true; the shell reports status 130 (128 + 2).
- 6New prompt
The shell prints a newline and continues.
In depth
From a line of text to a command structure
Do not run commands while you parse. First turn the line into tokens, then turn the tokens into a structure, then execute the structure. This keeps each step small and testable.
The tokenizer walks the line one character at a time. Spaces and tabs end a word. The characters |, <, > and & are operators and become tokens of their own even without spaces, so ls>out gives three tokens. Inside double or single quotes, spaces are kept, so "my file.txt" is one word. strtok cannot do this because it knows nothing about quotes, so write a small state machine instead.
The parser then reads tokens left to right. Words go into the current stage's argv. A | starts a new stage. A < or > must be followed by a word, which becomes the input or output file. A final & marks the whole job as background. Report errors like a missing file name after > before forking anything.
- Each stage needs its own argv array ending with NULL
- >> means open with O_APPEND instead of O_TRUNC
- Reject empty stages such as ls | | wc
- Stage 1
- argv: sort
- stdin: in.txt
- stdout: pipe to stage 2
- Stage 2
- argv: uniq -c
- stdin: pipe from stage 1
- stdout: out.txt
Redirection with open and dup2
Redirection happens in the child, after fork and before exec. For < file, the child opens the file read-only. For > file, it opens it with O_WRONLY | O_CREAT | O_TRUNC and mode 0644. Then dup2(fd, 0) or dup2(fd, 1) makes descriptor 0 or 1 point at the same open file, and the child closes the original fd so it does not leak into the new program.
The parent shell never touches its own descriptors 0 and 1, so the next prompt still goes to the terminal. If open fails, the child prints the error with perror and calls _exit(1). Use _exit, not exit, in a child that failed: exit would run atexit handlers and flush stdio buffers copied from the parent, which can print the same text twice.
If execvp fails, the convention from bash is exit status 127 for command not found (ENOENT) and 126 for found but not executable (EACCES). Users and scripts rely on these numbers.
Pipelines: the order of every call
For a pipeline of N commands you need N-1 pipes. The shell creates a pipe, forks the left child, which does dup2(p[1], 1), and forks the right child, which does dup2(p[0], 0). Each child then closes both original pipe ends before exec.
The parent must close both ends too. This is the most common bug in student shells. A reader only sees end of file when every write end is closed. If the shell still holds p[1], wc -l waits forever for more input, and the pipeline hangs.
For long pipelines, do not create all pipes at once. Keep only the read end left from the previous stage, create the next pipe, fork, and close what the parent no longer needs inside the loop. The shell then holds at most two pipe descriptors at any moment. Wait for every child, and report the exit status of the last stage, just like bash does by default.
- Shell to Kernel: pipe(p) gives p[0] and p[1]1pipe(p) gives p[0] and p[1]
- Shell to Child: ls: fork2fork
- Child: ls to Kernel: dup2(p[1], 1), close ends, exec ls3dup2(p[1], 1), close ends, exec ls
- Shell to Child: wc: fork4fork
- Child: wc to Kernel: dup2(p[0], 0), close ends, exec wc5dup2(p[0], 0), close ends, exec wc
- Shell to Kernel: close(p[0]) and close(p[1])6close(p[0]) and close(p[1])
- Child: ls to Child: wc: bytes flow through the pipe, then EOF7bytes flow through the pipe, then EOF
- Child: wc to Shell: exit status collected by waitpid8exit status collected by waitpid
Signals: Ctrl-C and SIGCHLD done safely
When you press Ctrl-C, the terminal sends SIGINT to every process in its foreground process group. In a simple shell, the shell and its children share one group, so the shell sets SIGINT to SIG_IGN for itself. An ignored signal stays ignored across exec, so each child must set SIGINT back to SIG_DFL before exec. Caught signals (with a handler) are reset to default by exec automatically.
Background jobs need reaping, or they stay as zombies. A SIGCHLD handler may only call async-signal-safe functions: waitpid and write are safe, but printf and malloc are not. The simplest safe design is a handler that only sets a volatile sig_atomic_t flag. Before each prompt, the main loop checks the flag and calls waitpid(-1, &status, WNOHANG) in a loop until it returns 0 or -1.
If your handler reaps children itself, save and restore errno inside it, and expect the foreground waitpid(pid) to sometimes fail with ECHILD because the handler got there first.
- Use sigaction with SA_RESTART so fgets is not cut short by SIGCHLD
- SA_NOCLDSTOP skips SIGCHLD for stopped (not exited) children
- Full job control adds setpgid per job and tcsetpgrp for the terminal
Learn it in 5 short steps
About 1h 35m each. Track them with a timer in your plan.
- 1Parse a command line into tokens~1h 35m
- 2Run commands with fork and execvp~1h 35m
- 3Add < > redirection and pipes~1h 35m
- 4Implement cd and exit built-ins~1h 35m
- 5Run background jobs and reap with SIGCHLD~1h 35m
Key points
- cd must be a built-in because chdir in a child does not affect the parent.
- Close all pipe ends in the parent after forking, or pipelines never finish.
- The shell ignores SIGINT itself, while children restore the default action.
- Reap background jobs with waitpid(-1, &status, WNOHANG) after SIGCHLD.
Key terms
Tap a card to flip it. 0/5 known
Examples
for (;;) {
char line[1024], *argv[64]; int argc = 0;
fputs("msh$ ", stdout); fflush(stdout);
if (!fgets(line, sizeof line, stdin)) break;
for (char *t = strtok(line, " \t\n"); t && argc < 63; t = strtok(NULL, " \t\n")) argv[argc++] = t;
argv[argc] = NULL;
if (argc == 0) continue;
if (strcmp(argv[0], "cd") == 0) { if (chdir(argc > 1 ? argv[1] : getenv("HOME")) < 0) perror("cd"); continue; }
if (strcmp(argv[0], "exit") == 0) break;
pid_t pid = fork();
if (pid == 0) { signal(SIGINT, SIG_DFL); execvp(argv[0], argv); perror(argv[0]); _exit(127); }
waitpid(pid, NULL, 0);
}The core loop; add pipes, redirection and & on top of it.
Redirection: sort < names.txt > sorted.txt
The parser finds argv = sort, in_path = names.txt and out_path = sorted.txt. After fork, the child calls a small helper for each redirection, then execs sort. sort reads fd 0 and writes fd 1 as usual, and has no idea they are files. If names.txt does not exist, the child prints "names.txt: No such file or directory" and exits with 1, and sort never starts. Note that errno is saved before perror, because perror itself could change it.
static void redirect(const char *path, int flags, int target) {
int fd = open(path, flags, 0644);
if (fd < 0 || dup2(fd, target) < 0) { perror(path); _exit(1); }
if (fd != target) close(fd);
}
/* in the child, after fork() returned 0 */
signal(SIGINT, SIG_DFL);
if (in_path) redirect(in_path, O_RDONLY, STDIN_FILENO);
if (out_path) redirect(out_path, O_WRONLY | O_CREAT | O_TRUNC, STDOUT_FILENO);
execvp(argv[0], argv);
int e = errno;
perror(argv[0]);
_exit(e == ENOENT ? 127 : 126);A two-stage pipeline: ls | wc -l
One pipe, two forks. The left child points fd 1 at the write end, the right child points fd 0 at the read end, and both close the original ends. The parent closes both ends right after the second fork and then waits for both children. Try deleting the parent's close(p[1]): run it and wc -l never prints, because it is still waiting for a writer that will never write. Needs unistd.h, sys/wait.h and stdio.h.
int p[2];
if (pipe(p) < 0) { perror("pipe"); return -1; }
pid_t a = fork();
if (a < 0) { perror("fork"); close(p[0]); close(p[1]); return -1; }
if (a == 0) { /* left side: ls */
dup2(p[1], STDOUT_FILENO); close(p[0]); close(p[1]);
execlp("ls", "ls", (char *)NULL); perror("ls"); _exit(127);
}
pid_t b = fork();
if (b == 0) { /* right side: wc -l */
dup2(p[0], STDIN_FILENO); close(p[0]); close(p[1]);
execlp("wc", "wc", "-l", (char *)NULL); perror("wc"); _exit(127);
}
close(p[0]); close(p[1]); /* parent must close both ends */
waitpid(a, NULL, 0); if (b > 0) waitpid(b, NULL, 0); else perror("fork");Quick reference
- Order in the child: fork, reset signals, open files, dup2, close originals, exec, then _exit on failure.
- > is O_WRONLY|O_CREAT|O_TRUNC, >> is O_WRONLY|O_CREAT|O_APPEND, < is O_RDONLY.
- N commands in a pipeline need N-1 pipes; the parent closes every pipe end it created.
- Exit status: WIFEXITED gives WEXITSTATUS; killed by signal n shows as 128 + n.
- 127 = command not found, 126 = found but not executable (bash convention).
- Reap background jobs: while (waitpid(-1, &st, WNOHANG) > 0) { ... }
- SIG_IGN survives exec; a handler does not. Reset SIGINT to SIG_DFL in children.
- Test with: strace -f -e trace=pipe2,dup2,execve,wait4 ./msh
Common mistakes
- Not reaping background jobs, which leaves zombies.
- Forgetting to flush the prompt before reading input.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Make the exit built-in accept an optional status (exit 3), and print the exit status of every foreground command that does not return 0, like [exit 1] or [signal 2].
- Exercise 2medium
Support background jobs: a trailing & runs the command without waiting, prints its PID, and the shell reports [done] PID before a later prompt, without leaving zombies.
- Exercise 3hard
Run a pipeline of any length (cmds[0] | cmds[1] | ... | cmds[n-1]) so that the shell never holds more than two pipe descriptors at once.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why can't cd be an external program like /bin/cd?
- The current directory belongs to each process. A child that calls chdir changes only its own directory and then exits, so the shell stays where it was. That is why cd, exit and export are built into the shell.
- What is the difference between execvp and execv?
- execvp searches the directories in PATH when the name has no slash, just like a shell does. execv needs the full path, such as /bin/ls.
- How do I make Ctrl-Z and fg work in my shell?
- That is full job control. Put each job in its own process group with setpgid, give that group the terminal with tcsetpgrp, and use waitpid with WUNTRACED to see stopped jobs. The GNU libc manual has a chapter on implementing a job control shell.
- How can I see what my shell is doing under the hood?
- Run it under strace -f, which follows child processes and shows every pipe, dup2, execve and wait4 call. It makes leftover pipe ends and failed execs easy to spot.