Survive the Terminal
Before a shell can run a command, the shell must measure, compare and copy strings. A copy must not write past the end of the buffer. The shell must also split a line into arguments, and loop until the user or the input stops. This section has three chapters. Each chapter builds one primitive by hand, and does not import it. The parts that need a real kernel (fork, exec and pipes) are in the operating system section.
strlenwalks the string each time that you call it. That cost is the reason why a slice stores its length.- A buffer for a 5-byte string needs 6 bytes. A bounds check that forgets the terminator passes a quick test, and then the copy writes one byte past the end.
- A trim returns a view, not a copy. You do not need to move bytes to remove spaces.
- A REPL has two exits, not one. If a loop only looks for
quit, the loop runs forever when a user presses Ctrl-D.
3 chapters.
- String Primitivesstrlen, compare, copy and trim, written out. The off-by-one error occurs in these functions.
- Tokenize a Command LineChange "ls -la /tmp" into the argv that a shell needs, and copy nothing.
- The Read-Eval-Print LoopFour steps and two ways to stop. Programmers often get the stop wrong.