See it in the room

C · Unix processes · 42 Common Core

minishell

A Unix shell in C: it reads a command line, splits it into commands and runs them as real processes joined by pipes.

The problem

The problem

Recreate the core of a shell: parse what people type, expand variables, run built-ins and programs, connect them with pipes and redirections, and behave correctly on signals and exit codes.

What I built

  • An interactive prompt on GNU Readline.
  • A tokenizer and parser with environment-variable expansion and heredocs (<<).
  • Pipelines of any length and the redirections <, >, >>.
  • The built-ins echo, cd, pwd, export, unset, env and exit, plus PATH lookup for everything else.
  • Shell-compatible exit statuses and interactive signal handling.

Technical decisions

  • Two layers: parsing builds commands, execution runs them, so each side can be tested on its own.
  • Built-ins that change the shell itself (cd, export, unset, exit) run in the shell process, not in a child.
  • Compiled with -Wall -Wextra -Werror.

What makes it hard

  • Every pipe end has to be closed in every process that does not use it, or a pipeline hangs.
  • Wiring stdin and stdout of each child with dup2() before it runs.

What I can do because of it

  • Understand how processes, file descriptors, pipes and signals work underneath every server and container.
  • Write a parser for a real input language.
  • Manage memory by hand in C without leaks.