In this assignment, you will develop a simple shell. A typical shell provides a command line prompt at which user commands are entered. It executes each command in a separate process. It also runs a command in the background if the ampersand (&) is used at the end of the command. You will use the system calls you have learned so far to implement such a shell.
There are three mandatory features that you will need to implement:
Execute user commands in separate processes, either in the foreground or in the background if & is used.
Implement some internal commands.
Implement a history feature.
Before you start the assignment, read this document in its entirety and understand it first. Unlike the assignments you probably did in your intro programming courses, there is no step-by-step guide in this assignment. It is your responsibility to understand what needs to be done and design the software properly that implements everything described in this document. This means that before even writing any code, you need to think about the necessary components you need to implement and also come up with your own step-by-step process. Write down your understanding of what needs to be implemented and how you're going to implement them. In addition, hand-draw diagrams that represent various components that you need and how they are related to each other. Note that you can learn how to design software more in CMPT 276. But you do not need that background in our assignments.
Lastly, make sure you record your entire work session(s).
Code Structure, CMake, and the Grader
You need to structure your code nicely according to what was discussed in A4. Also, you need to use CMake as the build system. We expect the following code structure.
a8
|-- CMakeLists.txt
|-- include
| -- *.h
|-- gtest
| -- (test source)
-- src
-- *.c
include/ contains a header file already. You will use the header file for this assignment. Also, you need to add your own header files there.
You need to create src/ and add all your .c files.
As we mentioned before, you need to make sure that you use the correct C and C++ compilers with CMake. As you know already, we use clang in this course, and the commands below set the C and C++ compilers for CMake to clang and clang++. What they do is setting the environment variables CC and CXX, which various programs commonly use to find the C and C++ compilers.
(which clang)
(which clang++)
In fact, this needs to be done every time you log in. In order to automate this, open your ~/.zshrc and add the above two commands at the end.
Assistant
exportCC=
exportCXX=
gtest/ contains the test cases for grading. We use Google Test to develop and run the test cases. You need to run these test cases and pass them. If a test case fails, it is your job to figure out why. This will often require you to look into the test case source code in gtest/. Though it is written in C++, it is similar enough to C and you should be able to understand it.
CMakeLists.txt includes directives to compile the test cases. However, this CMakeLists.txt is not complete and cmake won't work. You need to add more directives to make it work. What you have learned from A4 should be enough to do it.
After you make cmake work, you can run the executable it generates to run the test cases. At the end of each run, you will see how many points you get. We use your CMakeLists.txt to generate this executable and run it for grading (though exact test cases might differ as explained below). Thus, you need to make sure that it gets generated and works correctly.
The test cases expect that there is an executable named shell in the build directory. That is the executable that you need to produce for your shell. Thus, you need to edit CMakeLists.txt to generate shell from your code. You can use shell for your own manual testing during development as well.
The test cases expect that regular messages/outputs go to the standard output stream and error messages/outputs go to the standard error stream. You need to use these streams appropriately.
You should be able to use regular CMake commands to generate the executable for test cases as well as shell, e.g., cmake -S . -B build && cmake --build build.
Remember that test cases provide an input and check the output, and they do nothing more than that. If a test case fails for you, go to the test case source, find out the input it uses and the output it expects, and start your own debugging process with the input. It is your job to figure out which test case fails and which part of the source you need to look at.
The test cases are not exactly the same as what we run for our own grading. This is to prevent you from hard-coding or customizing your implementation tailored to our test cases. For example, to test an invalid command, we use a particular invalid command in the test source. This is not exactly the same as what we use for our own grading. Generally, you should consider the provided test cases as examples or specific instances of general cases.
Still rest assured---if you do not hard-code or customize your implementation tailored to our test cases, what you get from running the test cases will indeed be what you get in the end.
Task 0: Shell Prompt & Basic Command Support
The first feature you need to implement is executing programs that a user enters at the prompt. You need to use the necessary system calls appropriately to implement this feature. Of course, you need to handle a user command as input and pass all arguments correctly for execution. There are two modes of execution for external programs.
Foreground execution: In this mode, you need to execute a program in a child process and wait until the child process terminates.
Background execution: In this mode, you need to execute a program in a child process but should not wait for the termination of the child process.
& at the end of a user-entered command means that the command should run in the background.
There are a few things to keep in mind.
For all error messages, use the macros defined in msgs.h for correct formatting.
Your shell prompt should always show the current working directory. For example, if the user is in the /home/cmpt201 folder, the prompt should be:
/home/cmpt201$
Use the getcwd() function to get the current directory. If getcwd() returns an error, display this error message: shell: unable to get current directory.
When a user enters a command, your shell needs to handle it properly. strtok_r() function might be helpful. Read the manpage for it.
For foreground execution, you need to wait for the exact process you fork and not for any other processes.
Since we do not wait for a background process to terminate, it can become a zombie process (where a child process terminates but the parent process doesn't wait on it). Thus, your shell should still wait on each background child process at some point to clean it up. There are many ways to achieve this, but for this assignment, you can make an additional waitpid() call every time a user enters a command. The following are some hints.
This waitpid() call should wait on any child process since you're cleaning up zombie processes. Use an appropriate pid for that.
This waitpid() call should return immediately if no child has exited. Use an appropriate option for that.
Consult the man page of waitpid() for the above two points.
Remember that there can be multiple background processes launched previously. Thus, a single call will not clean up all of them. You need to use a loop to clean up all zombie processes.
For input/output, use read() and write() since we need to handle a signal in the next task. Other functions like printf() do not play nicely with signals. To see the list of functions safe for use with signals, run man signal-safety.
If you encounter an error when reading a user command with read(), you need to print out this error message: shell: unable to read command.
If fork() fails, print out this error message: shell: unable to fork.
If exec fails, print out this error message: shell: unable to execute command.
If wait fails, print out this error message: shell: unable to wait for child.
Task 1: Internal Commands and SIGINT
The second task is to implement some internal commands.
Your shell should implement a few internal commands described below. Internal commands are built-in commands of the shell itself, as opposed to a separate program that is executed. You should not fork new processes for internal commands as they are built-in. All the commands should be case-sensitive. For all error messages, use the macros defined in msgs.h for correct formatting.
exit: Exit the shell program. If the user provides any argument, abort the operation (i.e., do not exit) and print out this error message: exit: too many arguments.
pwd: Display the current working directory. Use the getcwd() function. If getcwd() returns an error, display this error message: pwd: unable to get current directory. If the user provides any argument, abort the operation and print out this error message: pwd: too many arguments.
cd: Change the current working directory. Use the chdir() function. If chdir() returns an error, display this error message cd: unable to change directory. If the user passed in more than one argument, abort the operation and print out this error message: cd: too many arguments. Additionally, implement the following features:
Change to the home directory if no argument is provided.
Support ~ for the home folder. For example, cd ~/tmp should change to the tmp directory under the current user's home directory. Issuing cd ~ should switch to the home directory.
Support - for changing back to the previous directory. For example, suppose that the current working directory is /home and you issued cd / to change to the root directory. Then, cd - should switch back to the /home directory.
You may find the getuid() and getpwuid() functions useful. They allow you to gather useful information about the current user.
help: Display help information on internal commands.
If the first argument is one of the internal commands, print out the command and the help message. For example, if the command is cd, print out cd: change the current directory.
If the first argument is not an internal command, print out the program name and the help message. For example, if the argument is ls, print out ls: external command or application.
If there is more than one argument, display this error message: help: too many arguments.
If there is no argument provided, list all the supported internal commands one by one with their corresponding help messages.
Your shell should not terminate when a user presses CTRL-C. Thus, you need to write a signal handler for SIGINT.
Have the signal handler display the help information (same as the help command).
Then re-display the command-prompt before returning.
A user can press CTRL-C anytime and interrupt system calls that are being executed. Thus, you need to properly check the return value of a system call to check if there was an error and also check errno to check which error it was. More specifically, you need to understand which value errno gets, if the error is caused by SIGINT. You need to handle SIGINT errors differently from other errors.
Task 2: History Feature
The next task is to modify your shell to provide a history feature that allows the user access up to the 10 most recently entered commands. Start numbering the user's commands at 0 and increment for each command entered. These numbers will grow past 9. For example, if the user has entered 35 commands, then the most recent 10 will be numbered 25 through 34. For all error messages, use the macros defined in msgs.h for correct formatting.
First, implement an internal command history which displays the 10 most recent commands executed in the shell. If there are less than 10 commands entered, display all the commands entered so far.
Display the commands in descending order (sorted by its command number).
The output should include both external application commands and internal commands.
Display the command number on the left, and the command (with all its arguments) on the right.
Use the macros in msgs.h.
If the command is run in the background using &, it must be added to the history with the &.
A sample output of the history command is shown below:
/home/cmpt201 history
30 history
29 cd /home/cmpt201
28 cd /proc
27 cat uptime &
26 cd /usr
25 ls
24 man pthread_create
23 ls
22 echo "Hello World from my shell!"
21 ls -la
/home/cmpt201
Next, implement the ! and related commands which allows users to run commands directly from the history list:
Command !n runs command number n. For example, !22 re-runs the 23rd command in the history. In the above example, this will re-run the echo command.
If n is not a number, or an invalid value (not one of the previous 10 command numbers) then display this error: history: command invalid.
Command !! runs the last command entered.
If there is no previous command, display the error message: history: no command entered. The history should remain empty.
When running a command using !n or !!, display the command from the history to the screen so the user can see what command they are actually running.
Neither the !! nor the !n commands are to be added to the history list themselves, but rather the command being executed from the history must be added. Here is an example.
/home/cmpt201echotesttest/home/cmpt201 !!
echo test
test
/home/cmpt201history15history14echotest13echotest12ls11manpthreadcreate10cd/hom
Other Requirements and Exceptions
Your code must not have any memory leaks or memory access errors. Use appropriate sanitizers and test your code to make sure you do not have any memory issues. Make sure you also use the debug option enabled in CMakeLists.txt to compile your code with debug information for testing. However, your code should work without the debug option as well. You should remove the debug option when you submit your code.
Your child processes may exit without freeing all their memory. You do not need to handle such cases.
You do not need to support either > (output redirection) or | (pipe).
Developing a simple shell is an excellent way to deepen your understanding of operating systems, process management, and system calls in C. Below is a structured approach to help you tackle each task outlined in your assignment. This guidance covers the key components and considerations without providing complete code, ensuring you engage with the material and develop your problem-solving skills.
1. Initial Setup and Code Structure
a. Directory Structure
Ensure your project follows the required directory structure:
include/: Place all your header files here, including any provided headers such as msgs.h.
src/: Implement your .c source files here.
gtest/: Contains Google Test source files for unit testing your shell.
b. CMake Configuration
Set up your CMakeLists.txt to compile both your shell and the test cases. Here's a basic outline:
cmake
cmake_minimum_required(VERSION 3.10)
project(SimpleShell C)
# Set C and C++ compilers to clang
set(CMAKE_C_COMPILER "clang")
set(CMAKE_CXX_COMPILER "clang++")
# Include directories
include_directories(include)
# Add source files
file(GLOB SRC_FILES src/*.c)
# Create executable for the shell
add_executable(shell ${SRC_FILES})
# Add test executable
enable_testing()
add_subdirectory(gtest)
# Assume gtest has its own CMakeLists.txt
Tips:
Ensure all your source and header files are correctly referenced.
Test your CMake setup early to catch configuration issues.
2. Task 0: Shell Prompt & Basic Command Support
a. Displaying the Prompt
Retrieve Current Directory: Use getcwd() to get the current working directory.
c
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) == NULL) {
write(STDERR_FILENO, "shell: unable to get current directory.\n", error_length);
}
Display Prompt: Use write() to output the prompt to STDOUT.
pid_t pid = fork();
if (pid < 0) {
write(STDERR_FILENO, "shell: unable to fork.\n", error_length);
continue;
}
In Child Process: Use execvp() to execute the command.
c
if (pid == 0) {
if (execvp(argv[0], argv) == -1) {
write(STDERR_FILENO, "shell: unable to execute command.\n", error_length);
exit(EXIT_FAILURE);
}
}
In Parent Process:
Foreground Execution: Use waitpid() to wait for the child process.
Background Execution: If the command ends with &, do not wait.
c
if (background) {
// Do not wait
} else {
if (waitpid(pid, &status, 0) == -1) {
write(STDERR_FILENO, "shell: unable to wait for child.\n", error_length);
}
}
e. Handling Zombie Processes
Non-Blocking Wait: Use waitpid() with WNOHANG in a loop to clean up any terminated background processes.
c
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
// Optionally, log or handle the termination
}
Tips:
Always check the return values of system calls for errors.
Use appropriate flags with waitpid() to handle different scenarios.
3. Task 1: Internal Commands and SIGINT
a. Implementing Internal Commands
Commands to Implement:
exit
pwd
cd
help
Implementation Guidelines:
No Forking: Handle internal commands within the main shell process.
Argument Checking: Ensure correct number of arguments and handle errors as specified.
Example: Handling exit Command
c
if (strcmp(argv[0], "exit") == 0) {
if (argc > 1) {
write(STDERR_FILENO, "exit: too many arguments.\n", error_length);
} else {
exit(EXIT_SUCCESS);
}
}
b. Handling cd Command
Change Directory: Use chdir().
Special Cases:
No Arguments: Change to home directory.
~: Expand to home directory.
-: Change to previous directory.
Example:
c
if (strcmp(argv[0], "cd") == 0) {
if (argc > 2) {
write(STDERR_FILENO, "cd: too many arguments.\n", error_length);
} else {
char *target_dir;
if (argc == 1 || strcmp(argv[1], "~") == 0) {
target_dir = getenv("HOME");
} else if (strcmp(argv[1], "-") == 0) {
target_dir = previous_directory; // Store this variable as needed
} else {
target_dir = argv[1];
}
if (chdir(target_dir) != 0) {
write(STDERR_FILENO, "cd: unable to change directory.\n", error_length);
} else {
// Update previous_directory accordingly
}
}
}
c. Implementing pwd and help Commands
pwd: Similar to prompt display using getcwd().
help: Display relevant help messages based on arguments.
Reentrancy: Within signal handlers, use only async-signal-safe functions like write().
SA_RESTART: Helps prevent system calls from failing with EINTR when interrupted by signals.
4. Task 2: History Feature
a. Maintaining Command History
Data Structure: Use a circular buffer or a fixed-size array to store up to the 10 most recent commands.
c
#define HISTORY_SIZE 10
char *history[HISTORY_SIZE];
int command_count = 0;
Adding Commands: After executing a command, store it in the history.
c
void add_to_history(const char *command) {
int index = command_count % HISTORY_SIZE;
free(history[index]); // Free if previously allocated
history[index] = strdup(command);
command_count++;
}
b. Implementing the history Command
Display Logic: Iterate through the history buffer and display commands in descending order with their command numbers.
c
if (strcmp(argv[0], "history") == 0) {
int start = (command_count < HISTORY_SIZE) ? 0 : command_count - HISTORY_SIZE;
for (int i = command_count - 1; i >= start; i--) {
int index = i % HISTORY_SIZE;
dprintf(STDOUT_FILENO, "%d\t%s\n", i, history[index]);
}
}
c. Implementing !n and !! Commands
!!: Re-execute the last command.
c
if (strcmp(argv[0], "!!") == 0) {
if (command_count == 0) {
write(STDERR_FILENO, "history: no command entered.\n", error_length);
} else {
char *last_command = history[(command_count - 1) % HISTORY_SIZE];
write(STDOUT_FILENO, last_command, strlen(last_command));
// Parse and execute the last command
}
}
!n: Re-execute command number n.
c
if (argv[0][0] == '!' && isdigit(argv[0][1])) {
int n = atoi(&argv[0][1]);
if (n < (command_count - HISTORY_SIZE) || n >= command_count) {
write(STDERR_FILENO, "history: command invalid.\n", error_length);
} else {
char *command_to_run = history[n % HISTORY_SIZE];
write(STDOUT_FILENO, command_to_run, strlen(command_to_run));
// Parse and execute the command
}
}
Tips:
Memory Management: Ensure you allocate and free memory correctly to avoid leaks.
Edge Cases: Handle scenarios where the history is not yet fully populated.
5. Additional Considerations
a. Error Handling
Always check the return values of system calls.
Use the msgs.h macros for standardized error messages.
b. Memory Management
Use tools like valgrind to check for memory leaks and access errors.
Allocate memory dynamically where necessary and free it appropriately.
c. Signal Safety
Within signal handlers, restrict to async-signal-safe functions (write(), etc.).
Avoid complex logic inside handlers; set flags if needed to handle post-signal processing.
d. Testing
Regularly compile and test each feature incrementally.
Use the provided Google Test cases to validate your implementation.
6. Example Workflow
Here's a high-level example of how your main loop might look:
c
while (1) {
// Display prompt
display_prompt();
// Read input
ssize_t bytes = read(STDIN_FILENO, buffer, sizeof(buffer) - 1);
if (bytes < 0) {
if (errno == EINTR) {
continue; // Interrupted by signal, redisplay prompt
}
write(STDERR_FILENO, "shell: unable to read command.\n", error_length);
continue;
}
buffer[bytes] = '\0';
// Parse command
parse_input(buffer, argv, &background);
// Handle internal commands
if (is_internal_command(argv)) {
execute_internal_command(argv);
add_to_history(buffer);
} else {
// Fork and execute external command
pid_t pid = fork();
if (pid == 0) {
// Child process
execvp(argv[0], argv);
// If execvp fails
write(STDERR_FILENO, "shell: unable to execute command.\n", error_length);
exit(EXIT_FAILURE);
} else if (pid > 0) {
// Parent process
if (!background) {
waitpid(pid, &status, 0);
}
add_to_history(buffer);
} else {
write(STDERR_FILENO, "shell: unable to fork.\n", error_length);
}
// Clean up zombie processes
clean_up_zombies();
}
}
Note: This is a simplified representation. You'll need to implement functions like display_prompt(), parse_input(), is_internal_command(), execute_internal_command(), and clean_up_zombies() based on the tasks outlined.
7. Resources for Further Learning
Man Pages: Utilize the man command to understand system calls (man fork, man execvp, man waitpid, man sigaction, etc.).
Signal Safety: Refer to Signal-Safe Functions for functions safe to use within signal handlers.
Google Test Documentation: Familiarize yourself with writing and running unit tests using Google Test.
C Programming Best Practices: Ensure your code is clean, well-documented, and follows best practices for memory management and error handling.
By following this structured approach, you'll be able to implement each feature methodically, ensuring robustness and compliance with the assignment requirements. Remember to test each component thoroughly before moving on to the next to simplify debugging and integration.