diff --git a/assignments/assignment-3/questions.md b/assignments/assignment-3/questions.md new file mode 100644 index 0000000000000000000000000000000000000000..d1c7801727bd1471627b798f0ee880abdf45aec4 --- /dev/null +++ b/assignments/assignment-3/questions.md @@ -0,0 +1,30 @@ +1. In this assignment I suggested you use `fgets()` to get user input in the main while loop. Why is `fgets()` a good choice for this application? + + > **Answer**: _start here_ + +2. You needed to use `malloc()` to allocte memory for `cmd_buff` in `dsh_cli.c`. Can you explain why you needed to do that, instead of allocating a fixed-size array? + + > **Answer**: _start here_ + + +3. In `dshlib.c`, the function `build_cmd_list(`)` must trim leading and trailing spaces from each command before storing it. Why is this necessary? If we didn't trim spaces, what kind of issues might arise when executing commands in our shell? + + > **Answer**: _start here_ + +4. For this question you need to do some research on STDIN, STDOUT, and STDERR in Linux. We've learned this week that shells are "robust brokers of input and output". Google _"linux shell stdin stdout stderr explained"_ to get started. + +- One topic you should have found information on is "redirection". Please provide at least 3 redirection examples that we should implement in our custom shell, and explain what challenges we might have implementing them. + + > **Answer**: _start here_ + +- You should have also learned about "pipes". Redirection and piping both involve controlling input and output in the shell, but they serve different purposes. Explain the key differences between redirection and piping. + + > **Answer**: _start here_ + +- STDERR is often used for error messages, while STDOUT is for regular output. Why is it important to keep these separate in a shell? + + > **Answer**: _start here_ + +- How should our custom shell handle errors from commands that fail? Consider cases where a command outputs both STDOUT and STDERR. Should we provide a way to merge them, and if so, how? + + > **Answer**: _start here_ \ No newline at end of file diff --git a/assignments/assignment-3/starter/dsh b/assignments/assignment-3/starter/dsh new file mode 100755 index 0000000000000000000000000000000000000000..ae8d8ec173dcc79ccda4203ccc7b0ec7a48cc812 Binary files /dev/null and b/assignments/assignment-3/starter/dsh differ diff --git a/assignments/assignment-3/starter/dsh_cli.c b/assignments/assignment-3/starter/dsh_cli.c new file mode 100644 index 0000000000000000000000000000000000000000..872ef851bb3b44eea8e6843800806c108aab44f9 --- /dev/null +++ b/assignments/assignment-3/starter/dsh_cli.c @@ -0,0 +1,97 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "dshlib.h" + +/* + * Implement your main function by building a loop that prompts the + * user for input. Use the SH_PROMPT constant from dshlib.h and then + * use fgets to accept user input. Since we want fgets to also handle + * end of file so we can run this headless for testing we need to check + * the return code of fgets. I have provided an example below of how + * to do this assuming you are storing user input inside of the cmd_buff + * variable. + * + * while(1){ + * printf("%s", SH_PROMPT); + * if (fgets(cmd_buff, ARG_MAX, stdin) == NULL){ + * printf("\n"); + * break; + * } + * //remove the trailing \n from cmd_buff + * cmd_buff[strcspn(cmd_buff,"\n")] = '\0'; + * + * //IMPLEMENT THE REST OF THE REQUIREMENTS + * } + * + * Also, use the constants in the dshlib.h in this code. + * SH_CMD_MAX maximum buffer size for user input + * EXIT_CMD constant that terminates the dsh program + * SH_PROMPT the shell prompt + * OK the command was parsed properly + * WARN_NO_CMDS the user command was empty + * ERR_TOO_MANY_COMMANDS too many pipes used + * + * Expected output: + * + * CMD_OK_HEADER if the command parses properly. You will + * follow this by the command details + * + * CMD_WARN_NO_CMD if the user entered a blank command + * CMD_ERR_PIPE_LIMIT if the user entered too many commands using + * the pipe feature, e.g., cmd1 | cmd2 | ... | + * + * See the provided test cases for output expectations. + */ + +int main() +{ + char *cmd_buff = malloc(SH_CMD_MAX * sizeof(char)); + int rc = 0; + command_list_t clist; + + clist.num = 0; + + while(1) { + printf("%s", SH_PROMPT); + + if(fgets(cmd_buff, ARG_MAX, stdin) == NULL) { + printf("\n"); + break; + } + + //remove the trailing \n from cmd_buff + cmd_buff[strcspn(cmd_buff, "\n")] = '\0'; + + if (strcmp(cmd_buff, EXIT_CMD) == 0) { + exit(0); + } + + //IMPLEMENT THE REST OF THE REQUIREMENTS + rc = build_cmd_list(cmd_buff, &clist); + + switch (rc) { + case OK: + printf(CMD_OK_HEADER, clist.num); + + for (int i = 0; i < clist.num; i++) { + printf("<%d>%s", i + 1, clist.commands[i].exe); + + if (strlen(clist.commands[i].args) > 0) { + printf("[%s]", clist.commands[i].args); + } + + printf("\n"); + } + break; + case WARN_NO_CMDS: + printf(CMD_WARN_NO_CMD); + break; + case ERR_TOO_MANY_COMMANDS: + printf(CMD_ERR_PIPE_LIMIT, CMD_MAX); + break; + } + } + return EXIT_SUCCESS; +} diff --git a/assignments/assignment-3/starter/dshlib.c b/assignments/assignment-3/starter/dshlib.c new file mode 100644 index 0000000000000000000000000000000000000000..3d84a1a771759f87ac10a137355fe55ecbb3c226 --- /dev/null +++ b/assignments/assignment-3/starter/dshlib.c @@ -0,0 +1,107 @@ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <ctype.h> + +#include "dshlib.h" + +/* + * build_cmd_list + * cmd_line: the command line from the user + * clist *: pointer to clist structure to be populated + * + * This function builds the command_list_t structure passed by the caller + * It does this by first splitting the cmd_line into commands by spltting + * the string based on any pipe characters '|'. It then traverses each + * command. For each command (a substring of cmd_line), it then parses + * that command by taking the first token as the executable name, and + * then the remaining tokens as the arguments. + * + * NOTE your implementation should be able to handle properly removing + * leading and trailing spaces! + * + * errors returned: + * + * OK: No Error + * ERR_TOO_MANY_COMMANDS: There is a limit of CMD_MAX (see dshlib.h) + * commands. + * ERR_CMD_OR_ARGS_TOO_BIG: One of the commands provided by the user + * was larger than allowed, either the + * executable name, or the arg string. + * + * Standard Library Functions You Might Want To Consider Using + * memset(), strcmp(), strcpy(), strtok(), strlen(), strchr() + */ + +void trim_spaces(char *str) { + while (*str && isspace((unsigned char)*str)) { + str++; + } + + size_t len = strlen(str); + while (len > 0 && isspace((unsigned char)str[len - 1])) { + str[len - 1] = '\0'; + len--; + } +} + +int build_cmd_list(char *cmd_line, command_list_t *clist) +{ + trim_spaces(cmd_line); + + char *cmd_tok = strtok(cmd_line, PIPE_STRING); + char *cmd[CMD_MAX + 1]; + int index = 0; + + while (cmd_tok != NULL) { + + //trim spaces + trim_spaces(cmd_tok); + + cmd[index] = cmd_tok; + index++; + + cmd_tok = strtok(NULL, PIPE_STRING); + + if (index > CMD_MAX) { + return ERR_TOO_MANY_COMMANDS; + } + } + + if (index == 0) { + return WARN_NO_CMDS; + } + + clist->num = 0; + + for (int i = 0; i < index; i++) { + char *exe = strtok(cmd[i], " "); + + if (strlen(exe) >= EXE_MAX) { + return ERR_CMD_OR_ARGS_TOO_BIG; + } + + strncpy(clist->commands[clist->num].exe, exe, EXE_MAX - 1); + clist->commands[clist->num].exe[EXE_MAX - 1] = '\0'; + + char *arg_tok = strtok(NULL, ""); + + if (arg_tok != NULL) { + trim_spaces(cmd_line); + if (strlen(arg_tok) >= ARG_MAX) { + return ERR_CMD_OR_ARGS_TOO_BIG; + } + + strncpy(clist->commands[clist->num].args, arg_tok, ARG_MAX - 1); + clist->commands[clist->num].args[ARG_MAX - 1] = '\0'; + } + else { + clist->commands[clist->num].args[0] = '\0'; + } + + clist->num++; + } + + return OK; + +} diff --git a/assignments/assignment-3/starter/dshlib.h b/assignments/assignment-3/starter/dshlib.h new file mode 100644 index 0000000000000000000000000000000000000000..1353bbd3ba39a4099cdf58ab8f8827e2d3e4e5aa --- /dev/null +++ b/assignments/assignment-3/starter/dshlib.h @@ -0,0 +1,50 @@ +#ifndef __DSHLIB_H__ +#define __DSHLIB_H__ + +// Constants for command structure sizes +#define EXE_MAX 64 +#define ARG_MAX 256 +#define CMD_MAX 8 +// Longest command that can be read from the shell +#define SH_CMD_MAX EXE_MAX + ARG_MAX + +typedef struct command +{ + char exe[EXE_MAX]; + char args[ARG_MAX]; +} command_t; + +typedef struct command_list +{ + int num; + command_t commands[CMD_MAX]; +} command_list_t; + +// Special character #defines +#define SPACE_CHAR ' ' +#define PIPE_CHAR '|' +#define PIPE_STRING "|" + +#define SH_PROMPT "dsh> " +#define EXIT_CMD "exit" + +// Standard Return Codes +#define OK 0 +#define WARN_NO_CMDS -1 +#define ERR_TOO_MANY_COMMANDS -2 +#define ERR_CMD_OR_ARGS_TOO_BIG -3 + +// starter code +#define M_NOT_IMPL "The requested operation is not implemented yet!\n" +#define EXIT_NOT_IMPL 3 +#define NOT_IMPLEMENTED_YET 0 + +// prototypes +int build_cmd_list(char *cmd_line, command_list_t *clist); + +// output constants +#define CMD_OK_HEADER "PARSED COMMAND LINE - TOTAL COMMANDS %d\n" +#define CMD_WARN_NO_CMD "warning: no commands provided\n" +#define CMD_ERR_PIPE_LIMIT "error: piping limited to %d commands\n" + +#endif \ No newline at end of file diff --git a/assignments/assignment-3/starter/makefile b/assignments/assignment-3/starter/makefile new file mode 100644 index 0000000000000000000000000000000000000000..9d20e5b5c474c8217fcc26b24b9a795b4b1a8127 --- /dev/null +++ b/assignments/assignment-3/starter/makefile @@ -0,0 +1,27 @@ +# Compiler settings +CC = gcc +CFLAGS = -Wall -Wextra -g + +# Target executable name +TARGET = dsh + +# Find all source and header files +SRCS = $(wildcard *.c) +HDRS = $(wildcard *.h) + +# Default target +all: $(TARGET) + +# Compile source to executable +$(TARGET): $(SRCS) $(HDRS) + $(CC) $(CFLAGS) -o $(TARGET) $(SRCS) + +# Clean up build files +clean: + rm -f $(TARGET) + +test: + ./test.sh + +# Phony targets +.PHONY: all clean \ No newline at end of file diff --git a/assignments/assignment-3/starter/test.sh b/assignments/assignment-3/starter/test.sh new file mode 100755 index 0000000000000000000000000000000000000000..6d586dbabea1cf80d3862450f1c62c8664db13d4 --- /dev/null +++ b/assignments/assignment-3/starter/test.sh @@ -0,0 +1,212 @@ +#!/usr/bin/env bats + +@test "Simple Command" { + run ./dsh <<EOF +test_command +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>test_commanddsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "Simple Command with Args" { + run ./dsh <<EOF +cmd -a1 -a2 +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>cmd[-a1-a2]dsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + + +@test "No command provided" { + run ./dsh <<EOF + +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>warning:nocommandsprovideddsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "Two commands" { + run ./dsh <<EOF +command_one | command_two +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS2<1>command_one<2>command_twodsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "three commands with args" { + run ./dsh <<EOF +cmd1 a1 a2 a3 | cmd2 a4 a5 a6 | cmd3 a7 a8 a9 +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS3<1>cmd1[a1a2a3]<2>cmd2[a4a5a6]<3>cmd3[a7a8a9]dsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "try max (8) commands" { + run ./dsh <<EOF +cmd1 | cmd2 | cmd3 | cmd4 | cmd5 | cmd6 | cmd7 | cmd8 +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS8<1>cmd1<2>cmd2<3>cmd3<4>cmd4<5>cmd5<6>cmd6<7>cmd7<8>cmd8dsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "try too many commands" { + run ./dsh <<EOF +cmd1 | cmd2 | cmd3 | cmd4 | cmd5 | cmd6 | cmd7 | cmd8 | cmd9 +exit +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>error:pipinglimitedto8commandsdsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} + +@test "kitchen sink - multiple commands" { + run ./dsh <<EOF +cmd1 +cmd2 arg arg2 +p1 | p2 +p3 p3a1 p3a2 | p4 p4a1 p4a2 +EOF + + # Strip all whitespace (spaces, tabs, newlines) from the output + stripped_output=$(echo "$output" | tr -d '[:space:]') + + # Expected output with all whitespace removed for easier matching + expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>cmd1dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>cmd2[argarg2]dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS2<1>p1<2>p2dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS2<1>p3[p3a1p3a2]<2>p4[p4a1p4a2]dsh>" + + # These echo commands will help with debugging and will only print + #if the test fails + echo "Captured stdout:" + echo "Output: $output" + echo "Exit Status: $status" + + # Check exact match + [ "$stripped_output" = "$expected_output" ] + + # Assertions + [ "$status" -eq 0 ] + +} \ No newline at end of file