Exercise: Builtin Commands¶
Tools: GCC, Make
Goal¶
Make cd and exit work in your shell.
Afterwards you will be able to say why some commands cannot run as a child process and must be handled by the shell itself.
Background¶
Every command so far ran in a child: fork, exec, wait.
cd cannot work that way.
A child that calls chdir() changes its own working directory and then exits; the shell, its parent, is left exactly where it was.
The same goes for exit: a child exiting ends the child, not the shell.
These are builtins: commands the shell runs itself, in its own process, instead of starting a program.
A real shell has a handful (cd, exit, export, ...); here you implement the two that matter.
shell.c now calls run_builtin() before run_command() for every line.
If run_builtin() handled the command it returns 1 and the shell reads the next line; otherwise it returns 0 and the line runs as a program, as before.
Your Task¶
Open shell.c and complete the TODO in run_builtin().
exit— end the shell withexit().cd— change directory withchdir(argv[1]); with no argument, usegetenv("HOME"). Report a failedchdir()withperror()and keep the shell running.- Return 1 for either builtin, 0 for anything else.
Build & Run¶
Check Your Work¶
cd /tmpthenpwd: the directory reported is the one you changed to;cdwith no argument thenpwdreports your home directory.cd /nonexistentprints an error and the shell keeps running;pwdis unchanged.- In
bash, runtype cdandtype ls: one is a shell builtin, the other a program onPATH. Say why a shell could not do it the other way round. - Run the shell under
strace -e trace=chdirand typecd /tmp: thechdirhappens in the shell's own process, with noclone/execvearound it.