introduction link to introduction
recently, my youtube feed prescribed low-level systems programming without AI to counterbalance my urge to become a full-time meat proxy.
in my opinion, that was a pretty ludicrous premise. coding without using an llm in 2026?
nevertheless, i decided to give it a shot and start with Stephen Brennan's classic "Write a Shell in C" guide!
(with the twist being that i would rewrite it in modern c++ instead of c)
like always, this blog simply serves as a documentation of the learning process involved. by the end of this, hopefully i get a better sense of why people enjoy systems programming and, by proxy, how a shell actually works.
cmake scaffolding link to cmake scaffolding
before any shell logic got written, i wanted to ensure my project was well scaffolded. reading through mainly steps 0, 1 and 4 of the official CMake tutorial, i got left with:
cmake_minimum_required(VERSION 4.4.2)
project(cppshell CXX)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # for my clangd (nvim) to stop complaining about header files not being linked properly
# add library support
add_library(cppcore)
target_sources(cppcore
PRIVATE
src/shell.cpp
PUBLIC
FILE_SET HEADERS
BASE_DIRS
include
FILES
include/shell.hpp
)
target_compile_features(cppcore PUBLIC cxx_std_23)
target_compile_options(cppcore PRIVATE -Wall -Wextra -Wpedantic)
# create executable
add_executable(cppshell)
target_sources(cppshell
PRIVATE
src/main.cpp
)
target_link_libraries(cppshell
PRIVATE
cppcore
)
target_compile_options(cppshell PRIVATE -Wall -Wextra -Wpedantic)this way, instead of compiling my cpp code with a deceptively large g++ command, i can do everything with cmake -B build && cmake --build build.
overall, the layout of the file is pretty self-explanatory.
we have a clean split of the shell logic into a cppcore library and link it into the cppshell executable to keep the main.cpp tiny,
making it easier to hook cppcore up to tests later on.
setting CMAKE_EXPORT_COMPILE_COMMANDS ON just tells CMake to spit out a compile_commands.json file,
letting language servers (like my clangd) know the project's compiler flags and include paths for autocomplete.
finally, the -Wall -Wextra -Wpedantic flags are just a personal preference to catch as many warnings as possible (all, extra, pedantic!).
this lets us get into the...
basic lifetime of a shell link to basic lifetime of a shell
just like in Brennan's guide, we break down a shell's lifetime into three stages:
- read and run any config files
- run the REPL (read, eval, print) loop => the main portion the original blog focuses on
- terminate the shell properly and exit
this leaves our src/main.cpp looking very minimal:
// copyright 2026 <eric zheng>
#include "shell.hpp"
int main() {
// load config file
// repl loop (read, eval, print loop)
repl_loop();
// perform any shutdown / cleanup
return 0;
}both the config and cleanup steps are left as placeholders for now:
- we don't load a config file yet because
cppshelldoesn't have any configurable state (like aliases, custom prompts, or a.cppshellrcformat) to read into. - we don't need manual cleanup yet because
c++RAII frees ourstd::strings andstd::vectors automatically oncerepl_loop()returns.
still, returning cleanly out of repl_loop() instead of calling std::exit() directly matters, since direct-exit skips local destructors, while unwinding back to main() gives us a clean hook later if we want to save history (and makes exit easier to test).
now, moving on to...
the REPL loop link to the REPL loop
if you've used a shell before, the basic repl_loop() flow is self-explanatory:
- print a prompt (in our case, just
>) - read the line that we input
- split it into separate arguments
- execute it
- repeat until told to stop
with placeholder functions, our repl_loop() looks something like:
void repl_loop() {
std::optional<std::string> line;
std::vector<std::string> args;
bool status{};
do {
// 1. print a prompt (in our cases, just `>`)
std::cout << "> ";
// 2. reads the line that we input
if (!(line = repl_read_line())) {
return;
}
// 3. split it into separate arguments
args = repl_split_line(*line);
// 4. execute it
status = repl_execute(args);
} while (status); // 5. repeat until told to stop
return;
}reading a line w/ repl_read_line() link to reading a line w/ repl_read_line()
in Brennan's c version, reading a line of arbitrary length takes ~30 lines of malloc, realloc, buffer-size math, and a getchar() loop.
fortunately in c++, we don't have to do all that!
std::getline and std::string handle all of the resizing automatically (RAII),
and std::optional<std::string> lets us signal "no more input" without magic values or raw pointers:
std::optional<std::string> repl_read_line() {
std::string buffer;
if (!std::getline(std::cin, buffer)) {
if (!std::cin.eof()) {
std::cerr << "cppshell: readline\n";
}
return std::nullopt;
}
return buffer;
}for repl_read_line(), we can see that it handles three main cases:
- (the most common) if there are no errors,
std::getline(std::cin, buffer)does not fail and we simply returnbuffer - if something went wrong reading
std::cin(like a closed or brokenstdin), we print an error tostd::cerrand returnstd::nulloptso the shell exits cleanly instead of looping forever - if we hit EOF (
std::cin.eof(), like pressingCtrl+Dor reaching the end of piped input), there's nothing left to read, so we returnstd::nulloptquietly and letrepl_loop()exit
file descriptors link to file descriptors
when testing how a broken stdin behaves, i ran into something confusing in zsh: closing stdin (fd 0, e.g. with exec <&-) didn't exit the REPL loop like it does in bash or cppshell.
turns out that's on purpose. in cppshell, std::cin reads directly from fd 0, so closing it breaks the REPL's input and forces the shell to exit. interactive zsh, on the other hand, duplicates its terminal input onto a higher file descriptor (starting at fd 10) so its own input loop stays out of the way of user redirections on fds 0–9. closing fd 0 breaks stdin for child commands, while zsh's own REPL keeps reading from fd 10 untouched.
parsing the line link to parsing the line
now we need to split the input line into a std::vector<std::string> of tokens.
similar to repl_read_line(), c++ gives us a much cleaner way to do this in <sstream> with std::istringstream.
it wraps a std::string so that you can read it with >>, just like std::cin.
it automatically skips leading, trailing, and repeated spaces or tabs, and evaluates to false when nothing is left:
std::vector<std::string> repl_split_line(const std::string &line) {
std::vector<std::string> tokens{};
std::string token{};
std::istringstream iss(line);
while (iss >> token) {
tokens.push_back(token);
}
return tokens;
}Note
what about quote-aware parsing? link to what about quote-aware parsing?
because istringstream splits strictly on whitespace, typing echo "hello world" produces three tokens {"echo", "\"hello", "world\""},
which isn't what we really want.
this implies that we need some sort of a bool flag to track whether we're inside quotes or not
(as well as considering a bunch of other edge cases like escaped quotes etc.) to get a proper shell parser.
how shells start processes link to how shells start processes
turns out, there's a standard way to run external programs in Unix (the POSIX process model) and shells are no exception:
- your shell calls
fork(), cloning the entire shell process into a parent and a child running at the exact same line fork()returns0inside the child, the child's PID (> 0) inside the parent, and-1if it failed- the child calls
execvp()to replace itself with the program you asked for (likels), and ifexecvp()succeeds, it never returns - the parent calls
waitpid()to pause until the child finishes
which gives us a basic framework for all the fork() paths:
pid == 0(child process)pid < 0(fork failed)pid > 0(parent process)
inside the child process specifically, we still need to figure out how to:
bridge std::vector<std::string> to execvp link to bridge std::vector<std::string> to execvp
since execvp is a POSIX c API with the signature:
int execvp(const char *file, char *const argv[]);this means we had to convert std::vector<std::string> into a char *const argv[] array:
// ...
if (pid == 0) {
std::vector<char *> argv;
for (std::string &arg : args) {
argv.push_back(arg.data());
}
argv.push_back(nullptr);
status = execvp(argv[0], argv.data());
// ... when looking through documentation, you'll usually see two ways to get a raw character pointer out of a std::string:
std::string::c_str(): always returns a read-onlyconst char *(great forcfunctions that only read a null-terminated string, likechdir)std::string::data(): returns a writablechar *when called on a non-conststd::string(sincec++17), orconst char *on aconstone
since c++11, both point to the same null-terminated ('\0') buffer, and both become invalid if the std::string is resized or destroyed.
here, execvp wants a non-const char *const argv[] because of its legacy c signature,
so arg.data() on a non-const std::string &arg is the right fit
(w/ a trailing nullptr because execvp's argument should be a null-terminated array).
next, we need to be able to handle:
child failures link to child failures
since fork() and execvp() are POSIX syscalls, they set the global errno variable when they fail,
meaning we can use perror() to automatically print the error message for us.
std::cerr is still useful for our own validation errors (like cd with too many arguments).
then, if execvp() fails, we need to exit the child process immediately instead of returning to the parent shell,
since otherwise the child would return straight back into the REPL loop and start running the shell again.
we choose to do this via _exit() instead of std::exit() so the child process exits silently without flushing any buffers or running any destructors (duplicated from the parent).
this gives us:
// ...
// 1. child process
if (pid == 0) {
std::vector<char *> argv;
for (std::string &arg : args) {
argv.push_back(arg.data());
}
argv.push_back(nullptr);
status = execvp(argv[0], argv.data());
// if `execvp` fails, we need to exit the child process immediately
if (status == -1) {
perror("cppshell");
_exit(EXIT_FAILURE);
}
// 2. fork failed
} else if (pid < 0) {
perror("cppshell");
}
// ...parent waiting for the child link to parent waiting for the child
finally, the parent process needs to wait for the child to finish before continuing the REPL loop, otherwise the next > prompt would collide with the child's output.
we do this with waitpid(), which pauses the parent until child pid either exits or gets killed by a signal.
on top of that, waitpid() collects the child's exit status from the process table so finished children don't stick around as zombie processes (which would eventually fill up the process table if left unchecked).
final loop link to final loop
here is the final repl_launch:
bool repl_launch(std::vector<std::string> &args) {
int status{};
pid_t pid = fork();
// 1. child process
if (pid == 0) {
std::vector<char *> argv;
for (std::string &arg : args) {
argv.push_back(arg.data());
}
argv.push_back(nullptr);
status = execvp(argv[0], argv.data());
// if `execvp` fails, we need to exit the child process immediately
if (status == -1) {
perror("cppshell");
_exit(EXIT_FAILURE);
}
// 2. fork failed
} else if (pid < 0) {
perror("cppshell");
// 3. parent process
} else {
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return true;
}shell builtin functions link to shell builtin functions
while the repl_launch() above handles launching external programs, there is also the need for builtin functions that run directly inside the shell itself.
think about common commands like cd and exit, which need to change the shell's own state instead of launching a new process.
if it ran in a forked child, the child would change its own directory and immediately exit, leaving the parent shell right where it started.
in Brennan's c version, builtins are wired up with two separate parallel arrays (one of command names, one of function pointers) looped over with strcmp.
in c++, we can keep each command name paired directly with its handler in a single std::unordered_map:
using BuiltinFn = bool (*)(const std::vector<std::string> &);
static const std::unordered_map<std::string_view, BuiltinFn> builtins{
{"cd", builtin_cd},
{"help", builtin_help},
{"exit", builtin_exit},
};using std::string_view as the key is nice here because std::string converts to std::string_view implicitly with zero copying when we call builtins.find(args[0]).
at the same time, you can not pass a std::string_view directly to c APIs like chdir or execvp.
a string_view only stores {pointer, length} and isn't guaranteed to end in '\0', whereas c APIs don't care about length at all: they just take a pointer and keep reading until they hit '\0'.
so if you handed chdir a string_view slice of "cd /tmp extra" pointing at "/tmp", it would read right past "/tmp" into " extra" until it finally ran into '\0'.
now, we can simply define all the builtin functions:
implementing cd link to implementing cd
for builtin_cd, we just wrap the POSIX chdir() syscall to change the current working directory of the shell:
bool builtin_cd(const std::vector<std::string> &args) {
int n{static_cast<int>(args.size())};
if (n == 1) {
const char *home{std::getenv("HOME")};
if (!home) {
std::cerr << "cppshell: no HOME directory set\n";
return true;
}
if (chdir(home) == -1) {
perror("cppshell");
}
} else if (n == 2) {
if (chdir(args[1].c_str()) == -1) {
perror("cppshell");
}
} else {
std::cerr << "cppshell: too many arguments\n";
}
return true;
}implementing help link to implementing help
for loop of doom... i would've created a custom struct for {fn, description} but this does the trick for now.
bool builtin_help(const std::vector<std::string> &) {
std::cout << "monoclonal's shell\n";
std::cout << "the following commands are built in:\n";
for (const auto &[name, fn] : builtins) {
std::cout << "- " << name << "\n";
}
return true;
}implementing exit link to implementing exit
to break out of the REPL loop:
bool builtin_exit(const std::vector<std::string> &) { return false; }Note
isn't history important? link to isn't history important?
history is written by the victors, so clearly i'm not a victor yet.
if i was to continue building cppshell, a history feature would definitely be on the cards,
but to implement it we would need a way to store state across multiple shell invocations, which is lowkey impossible with a raw function pointer.
even if you want to include capturing lambdas, you still can't do that with a pointer since it can't physically hold the captured state, and the global map can't capture a local variable without making it global.
therefore, we realistically either have to switch to std::function (so lambdas can capture state) or keep raw function pointers and pass a separate ShellState & struct into every BuiltinFn.
putting together builtins and processes link to putting together builtins and processes
with builtins and repl_launch both done, repl_execute just checks if the first token is a built-in function, and if not, launches it as an external process:
bool repl_execute(std::vector<std::string> &args) {
if (args.empty()) {
std::cerr << "cppshell: no arguments\n";
return true;
}
if (auto it = builtins.find(args[0]); it != builtins.end()) {
return it->second(args);
}
return repl_launch(args);
}putting it all together link to putting it all together
with everything all set-up, i can finally round off my blog with a linkedin-style message:
i'm happy to share that the entire src/shell.cpp ended up around 140 lines, compiles with zero warnings, and handles the base shell cases cleanly!
i would like to thank Stephen Brennan for the phenomenal introduction to the POSIX process model,
and also the c++ standard library for making my life simultaneously easier and harder at the same time.
in the next chapter, i am pleased to announce that i will be spending my spare time looking at system design diagrams of polymarket market manipulation software!
comments:
so far
loading comments…
no comments yet. be the first to leave one.
comments couldn’t load right now. try again
sent:
thanks! your comment is with me now. it’ll show up here once i’ve read it.
leave another