
Recall first from exec and wait
- Successful exec keeps the PID and preserves descriptors unless close-on-exec is set.
- Arguments and environments are null-terminated arrays of pointers to terminated strings.
- Interpret wait status only with the matching WIF and W macros.
Build mysh v1 around one child
4 min readA forked child can exec a program and its parent can read the result. This lesson answers how to build a shell around one child and what stays shared after fork.
Start with intentionally small command syntax: words separated by spaces or tabs. There is no quote processing, wildcard expansion, pipeline, redirection or background execution. Characters such as * and | become ordinary argument text. Do not use this parser for general shell scripts.
1Keep shell changes in the parent
cd must call chdir() in the shell itself. Changing a child's working directory leaves the parent's directory unchanged. exit also belongs in the parent. This version accepts cd directory, uses HOME for bare cd, and accepts bare exit to return the last result.
2Implement the launch loop
Save this complete program as mysh.c. _POSIX_C_SOURCE enables the POSIX declarations used by getline() and strtok_r() under strict C compilation. getline() returns a signed byte count, so its result type is ssize_t.
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
enum { MAX_ARGS = 64 };
int main(void)
{
char *line = NULL;
size_t capacity = 0;
int last = 0;
int interactive = isatty(STDIN_FILENO);
for (;;) {
if (interactive) {
if (fputs("mysh> ", stdout) == EOF || fflush(stdout) == EOF) {
last = 1;
break;
}
}
errno = 0;
ssize_t length = getline(&line, &capacity, stdin);
if (length == -1) {
if (errno == EINTR) {
clearerr(stdin);
continue;
}
if (!feof(stdin)) {
perror("getline");
last = 1;
}
break;
}
if (memchr(line, '\0', (size_t)length) != NULL) {
fputs("embedded zero byte rejected\n", stderr);
last = 2;
continue;
}
char *args[MAX_ARGS + 1];
size_t count = 0;
char *save = NULL;
char *word = strtok_r(line, " \t\r\n", &save);
while (word != NULL && count < MAX_ARGS) {
args[count++] = word;
word = strtok_r(NULL, " \t\r\n", &save);
}
if (word != NULL) {
fputs("too many arguments\n", stderr);
last = 2;
continue;
}
args[count] = NULL;
if (count == 0)
continue;
if (strcmp(args[0], "exit") == 0) {
if (count != 1) {
fputs("usage: exit\n", stderr);
last = 2;
continue;
}
break;
}
if (strcmp(args[0], "cd") == 0) {
if (count > 2) {
fputs("usage: cd [directory]\n", stderr);
last = 2;
continue;
}
const char *directory = count == 2 ? args[1] : getenv("HOME");
if (directory == NULL) {
fputs("cd: HOME is absent\n", stderr);
last = 1;
} else if (chdir(directory) == -1) {
perror("cd");
last = 1;
} else {
last = 0;
}
continue;
}
if (fflush(NULL) == EOF) {
perror("fflush");
last = 1;
continue;
}
pid_t child = fork();
if (child == -1) {
perror("fork");
last = 1;
continue;
}
if (child == 0) {
execvp(args[0], args);
int saved_error = errno;
perror(args[0]);
_exit(saved_error == ENOENT ? 127 : 126);
}
int status;
pid_t collected;
do {
collected = waitpid(child, &status, 0);
} while (collected == -1 && errno == EINTR);
if (collected == -1) {
perror("waitpid");
last = 1;
break;
}
if (WIFEXITED(status)) {
last = WEXITSTATUS(status);
printf("child %jd exited: %d\n", (intmax_t)child, last);
} else if (WIFSIGNALED(status)) {
int signal_number = WTERMSIG(status);
last = 128 + signal_number;
printf("child %jd terminated by signal: %d\n",
(intmax_t)child, signal_number);
}
}
free(line);
return last;
}
args points into line, which remains valid through the child's exec attempt. The parent waits before reusing it. Saving errno before perror() preserves the error used to choose failure status.
The values 126 and 127 are useful shell conventions for launch failures. They do not prove that exec failed: a successfully launched program can return either value itself. The shell prints the actual terminating signal separately, keeping that evidence visible.
3Compile and exercise observable behavior
Compile on Linux, then feed simple commands through a pipe. The outer shell's printf supplies input; it is not syntax implemented by mysh.
cc -std=c11 -Wall -Wextra -Wpedantic -O0 -g mysh.c -o mysh
printf '/bin/true\n/bin/false\nmissing-training-command\nexit\n' | ./mysh
./mysh
Check that each external command produces a status line and the prompt returns. Check that cd /tmp changes a subsequent pwd. Empty lines should launch nothing. The shell's own final status follows its last command or built-in result.
This version is single-threaded; its child-side perror() relies on that scope. Ctrl-C can affect the shell, and a stopped child can leave it waiting. Signals and job control come next. Use interactive mode for commands that read stdin: a script reader's getline() can read ahead, leaving the child without expected input.
getline() grows its allocation to fit input. The argument count is bounded, but line memory is not. A product accepting untrusted input needs a bounded reader that consumes and rejects oversized lines. On a small board, check that external applet paths actually exist instead of assuming a desktop filesystem layout.
What stays separate and what stays shared
5 min readSuppose you open a regular file before fork. The child reads three bytes and exits. After the parent collects it, a normal read() through the inherited descriptor starts at the advanced position. The child changed a shared kernel file offset, not a variable in the parent's heap.
An a kernel open-file object holding state such as the current offset and file status flags, referenced by descriptors is the shared object here. The parent's and child's descriptor tables are distinct. Both tables can refer to the same description.
Closing a descriptor in the child removes its reference. It does not close the parent's descriptor. Changing a descriptor flag such as FD_CLOEXEC also affects only that descriptor entry. In contrast, changing a shared status flag such as O_NONBLOCK affects users of the same open file description. Opening the path again creates another description with an independent offset.
1Separate C buffers from kernel state
printf() may retain bytes inside the C library until flushing. Fork duplicates that buffer in private memory. If both processes later call exit(), each can write its copy, producing duplicated output. Redirection to a file often exposes this because newline output need not flush a fully buffered stream.
Flush pending output before fork when that output belongs to the parent. Then use _exit() on a child exec failure. Successful exec discards copied buffers. This bug combines deterministic buffer duplication with timing-dependent ordering; waiting afterward does not undo the duplication.
Buffered input needs care too. A parent can read ahead from a file into its private stdio buffer. The shared kernel offset then lies beyond the bytes the parent has consumed logically. A child reading the inherited descriptor sees that advanced offset, not the parent's buffered bytes. Avoid mixing independent buffered readers around fork without explicit coordination.
2Track preserved and reset attributes
A signal's disposition is its configured action: default, ignore or a handler function. A signal mask lists signals temporarily blocked from delivery. Pending signals have been generated but not yet delivered. These terms become practical in the next lesson.
| Attribute | After ordinary fork | After successful exec |
|---|---|---|
| PID | New child PID | Preserved |
| Private address space | Logically copied | Replaced |
| Working directory and creation mask | Copied | Preserved |
| Caught signal dispositions | Copied | Reset to default |
| Ignored signal dispositions | Copied | Preserved on Linux |
| Signal mask | Copied from calling thread | Preserved |
| Pending signals | Child starts empty | Preserved |
| Descriptors | Copied references | Kept unless close-on-exec |
atexit registrations |
Copied | Discarded |
The creation mask, set by umask(), removes permissions from newly created files. Real user and group IDs survive exec. Effective credentials can change for specially marked executable files, subject to Linux security restrictions.
Traditional process-associated fcntl record locks are not inherited by the child. The parent's locks normally survive its own exec, although closing a descriptor for that file can release them. Linux open-file-description locks and flock() locks follow the inherited open description instead. Say which lock family you mean.
Going deeperFollow the objects through kernel source
The kernel represents a task with task_struct. Its memory description uses mm_struct; descriptors are reached through files_struct. In your board's matching Linux source tree, start in kernel/fork.c for creation, fs/exec.c for replacement, and kernel/exit.c for exit and waiting. Memory write-fault handling lives under mm/, notably mm/memory.c. These internal structures and helpers can evolve.
Do not equate a process's virtual size with newly copied physical memory after fork. Page-table work, task allocation and later write faults contribute different costs. On a memory-limited board, latency can increase when either side dirties many private pages, even if creation itself seemed cheap.
Going deeperForking a threaded process
Threads share process memory and resources. Fork copies only the calling thread, but memory can contain locks owned by vanished threads. A mutex permits one lock owner at a time. Child-side allocation or stdio may deadlock on inherited library state.
After fork in a multithreaded process, restrict the child to async-signal-safe operations until exec. Async-signal-safe means the function can run safely when it interrupts another operation in the same process. write(), close(), execve() and _exit() are key building blocks. Ordinary formatting and memory allocation do not qualify.
pthread_atfork(prepare, parent, child) registers callbacks around fork. Prepare callbacks run in reverse registration order; parent and child callbacks run in registration order. They help coordinate known state, but cannot repair arbitrary third-party locks or remove the child-side safety restriction. Prefer controlled spawn actions when they express the setup you need.
Key takeaways
- Private memory changes separate after fork, but inherited descriptors share open file descriptions.
- cd and exit run in the shell itself; changing a child's working directory does not move the parent.
- fork copies descriptor entries while the open file description and its offset stay shared, so one side's reads and writes move the position for both.
- stdio buffers are duplicated in private memory by fork, so both sides flushing can duplicate output, which redirection makes visible.
Reflect
- Explain to a colleague, in two sentences: implement mysh v1 with built-ins, fork, execvp and checked child collection.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.