CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 3 of 6 · 3 min read

The code

The program below is split into three pieces for reading. Together they form one file, mysh.c.

In plain words: Piece one reads a line and splits it into words. The function strtok cuts a string at spaces, tabs and newlines. A word > is treated specially: the word after it is the output file.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAXARGS 32

int main(void) {
    char line[1024];
    for (;;) {
        printf("mysh> ");
        fflush(stdout);
        if (!fgets(line, sizeof line, stdin)) break;   /* end of input */
        char *args[MAXARGS], *outfile = NULL;
        int n = 0;
        for (char *t = strtok(line, " \t\n"); t && n < MAXARGS - 1;
             t = strtok(NULL, " \t\n")) {
            if (strcmp(t, ">") == 0) outfile = strtok(NULL, " \t\n");
            else args[n++] = t;
        }
        args[n] = NULL;
        if (n == 0) continue;

Piece two handles the two commands that the shell does itself:

        if (strcmp(args[0], "exit") == 0) break;
        if (strcmp(args[0], "cd") == 0) {
            if (n < 2 || chdir(args[1]) != 0) perror("cd");
            continue;
        }

Piece three starts everything else. The child redirects its output if asked, then replaces itself with the command. The parent waits and reports a non-zero exit status.

        pid_t pid = fork();
        if (pid < 0) { perror("fork"); continue; }
        if (pid == 0) {
            if (outfile) {
                int fd = open(outfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
                if (fd < 0) { perror(outfile); _exit(1); }
                dup2(fd, STDOUT_FILENO);
                close(fd);
            }
            execvp(args[0], args);
            perror(args[0]);
            _exit(127);
        }
        int status;
        waitpid(pid, &status, 0);
        if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
            printf("[exit %d]\n", WEXITSTATUS(status));
    }
    return 0;
}

Here is a session on the test machine. The input was piped in, so the prompts run together on the output:

mysh> hello world          (from: echo hello world)
mysh> ls: cannot access '/nonexistent': No such file or directory
[exit 2]
mysh> nosuch: No such file or directory
[exit 127]

ls ended with status 2 because the path does not exist. The command nosuch was not found, so execvp failed in the child, which printed the message and left with status 127. That number is the usual shell convention for "command not found" (127 is the value the child chose to return, as in page 3).

The whole shell is 53 lines, with prompts and error handling.

Check yourself: 1. Why does the child call _exit(127) after a failed execvp? 2. What does strtok do with the line? 3. What does the parent do while the child runs?