Skip to content
Snippets Groups Projects
Commit 65eec2b9 authored by vht24's avatar vht24
Browse files

Assignment 5

parent d9120762
No related branches found
No related tags found
No related merge requests found
#!/usr/bin/env bats
############################ DO NOT EDIT THIS FILE #####################################
# File: assignement_tests.sh
#
# DO NOT EDIT THIS FILE
#
# Add/Edit Student tests in student_tests.sh
#
# All tests in this file must pass - it is used as part of grading!
########################################################################################
@test "Pipes" {
run "./dsh" <<EOF
ls | grep dshlib.c
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="dshlib.cdsh3>dsh3>cmdloopreturned0"
# 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"
echo "${stripped_output} -> ${expected_output}"
# Check exact match
[ "$stripped_output" = "$expected_output" ]
# Assertions
[ "$status" -eq 0 ]
}
#!/usr/bin/env bats
# File: student_tests.sh
#
# Create your unit tests suit in this file
@test "Example: check ls runs without errors" {
run ./dsh <<EOF
ls
EOF
# Assertions
[ "$status" -eq 0 ]
}
@test "Clear Command" {
run "./dsh" <<EOF
clear
EOF
stripped_output=$(echo "$output" | sed 's/\x1B\[[0-9;]*[a-zA-Z]//g' | tr -d '[:space:]')
expected_output="dsh3>dsh3>cmdloopreturned0"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
@test "cd" {
run "./dsh" <<EOF
cd
EOF
stripped_output=$(echo "$output" | tr -d '[:space:]')
expected_output="dsh3>dsh3>cmdloopreturned0"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
@test "exit" {
run "./dsh" <<EOF
exit
EOF
stripped_output=$(echo "$output" | tr -d '[:space:]')
expected_output="dsh3>cmdloopreturned-7"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
@test "Pipes - ps aux | grep dsh" {
run "./dsh" <<EOF
ps aux | grep dsh
EOF
[ "$status" -eq 0 ]
}
@test "Simple Echo Command" {
run "./dsh" <<EOF
echo hello world
EOF
stripped_output=$(echo "$output" | tr -d '[:space:]')
expected_output="helloworlddsh3>dsh3>cmdloopreturned0"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
@test "Invalid Command Handling" {
run "./dsh" <<EOF
invalidcmd
EOF
stripped_output=$(echo "$output" | tr -d '[:space:]')
expected_output="execvp:Nosuchfileordirectorydsh3>dsh3>dsh3>cmdloopreturned0"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
@test "output - echo > tempfile" {
run "./dsh" <<EOF
echo uhh > tempfile
cat tempfile
rm tempfile
EOF
stripped_output=$(echo "$output" | tr -d '[:space:]')
expected_output="uhhdsh3>dsh3>dsh3>dsh3>cmdloopreturned0"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
@test "Append - echo >> tempfile" {
run "./dsh" <<EOF
echo uhh > tempfile
echo "uuuu" >> tempfile
cat tempfile
rm tempfile
EOF
stripped_output=$(echo "$output" | tr -d '[:space:]')
expected_output="uuuuuhhdsh3>dsh3>dsh3>dsh3>dsh3>cmdloopreturned0"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
@test "Input - cat < tempfile" {
echo "oowwoo" > tempfile
run "./dsh" <<EOF
cat < tempfile
rm tempfile
EOF
stripped_output=$(echo "$output" | tr -d '[:space:]')
expected_output="oowwoodsh3>dsh3>dsh3>cmdloopreturned0"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
@test "Redirection with Pipeline - cat < testfile.txt | grep o" {
echo "oowwoo" > testfile.txt
run "./dsh" <<EOF
cat < testfile.txt | grep o
rm testfile.txt
EOF
stripped_output=$(echo "$output" | tr -d '[:space:]')
expected_output="oowwoodsh3>dsh3>dsh3>cmdloopreturned0"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
@test "missing File for <" {
run "./dsh" <<EOF
cat < not_a_real_file.file
EOF
stripped_output=$(echo "$output" | tr -d '[:space:]')
expected_output="openinputfile:Nosuchfileordirectorydsh3>dsh3>dsh3>cmdloopreturned0"
echo "Output: $output"
echo "Exit Status: $status"
echo "${stripped_output} -> ${expected_output}"
[ "$stripped_output" = "$expected_output" ]
[ "$status" -eq 0 ]
}
#include <stdio.h>
#include <stdlib.h>
#include <zlib.h>
#include "dragon_data.h" // Include the embedded binary data
#define DRAGON_BUFFER_SIZE 100000
// EXTRA CREDIT - print the Drexel dragon from embedded binary
extern void print_dragon() {
unsigned char *decompressed_data = (unsigned char *)malloc(DRAGON_BUFFER_SIZE);
if (!decompressed_data) {
fprintf(stderr, "Memory allocation failed!\n");
return;
}
uLongf decompressed_size = DRAGON_BUFFER_SIZE;
// Ensure correct decompression
if (uncompress(decompressed_data, &decompressed_size, DRAGON_BIN, DRAGON_BIN_SIZE) != Z_OK) {
fprintf(stderr, "Decompression fail\n");
free(decompressed_data);
return;
}
printf("%s", decompressed_data);
free(decompressed_data);
}
\ No newline at end of file
#ifndef DRAGON_DATA_H
#define DRAGON_DATA_H
const unsigned char DRAGON_BIN[] = { 0x78, 0x9c, 0xb5, 0xd6, 0x41, 0xa2, 0x83, 0x20, 0x0c, 0x04, 0xd0, 0x3d, 0xa7, 0x60, 0x93, 0x7b, 0xe4, 0xfe, 0xa7, 0xea, 0xaf, 0x4a, 0x0a, 0xc9, 0x4c, 0x82, 0xad, 0x9f, 0x45, 0x6b, 0x21, 0xf8, 0x48, 0x44, 0x6d, 0xeb, 0x0f, 0x35, 0x95, 0xbf, 0x46, 0xc6, 0xda, 0x23, 0x82, 0x48, 0x42, 0x3c, 0x84, 0x14, 0xc6, 0x03, 0x88, 0x5c, 0xc6, 0x8c, 0xe8, 0xc3, 0x88, 0x58, 0x73, 0x3d, 0x5f, 0x20, 0x36, 0xf3, 0xfd, 0xa9, 0xbe, 0x5b, 0xac, 0x77, 0x84, 0x2d, 0xfb, 0x60, 0x03, 0x11, 0xd8, 0xb2, 0x31, 0x9f, 0x4a, 0x89, 0xa4, 0x27, 0x59, 0x7e, 0x52, 0xa3, 0x44, 0xb2, 0xa5, 0x86, 0xf3, 0xda, 0xb9, 0x57, 0xa3, 0x40, 0x32, 0x41, 0xcf, 0xba, 0xe3, 0xe5, 0xdf, 0x40, 0xd2, 0x34, 0x58, 0x2a, 0x12, 0xef, 0x98, 0xdf, 0x10, 0xae, 0xff, 0x27, 0x72, 0x55, 0x50, 0x21, 0x62, 0x41, 0x09, 0x51, 0xd3, 0x63, 0x1c, 0x96, 0x0b, 0x67, 0x6a, 0xeb, 0x0a, 0x15, 0x98, 0x7b, 0x63, 0x88, 0x22, 0x64, 0x09, 0xa2, 0x2b, 0xde, 0x29, 0x23, 0x2b, 0x7b, 0xeb, 0x3e, 0x64, 0x4e, 0x85, 0x9d, 0x60, 0x1e, 0x50, 0x16, 0x34, 0x21, 0x9f, 0x60, 0x3f, 0x24, 0x5c, 0x01, 0x77, 0x48, 0xc6, 0x18, 0x12, 0x8c, 0xe4, 0x9a, 0x24, 0x08, 0x74, 0x06, 0x12, 0x8d, 0x50, 0x7a, 0x3e, 0x52, 0x41, 0x8d, 0x0d, 0xa4, 0x4a, 0x89, 0xcc, 0x4f, 0xe9, 0xf4, 0x9a, 0xc4, 0xb2, 0x40, 0x44, 0xcf, 0x33, 0x21, 0x65, 0x1c, 0xde, 0xc9, 0x84, 0xec, 0x6e, 0x96, 0xdc, 0xa7, 0x6b, 0xca, 0x04, 0x6d, 0x30, 0xd7, 0x14, 0xf6, 0xa7, 0x15, 0x7c, 0x8f, 0xb4, 0xee, 0x82, 0x57, 0xc4, 0xcd, 0x55, 0xac, 0xa7, 0x57, 0xe9, 0x40, 0xdc, 0x83, 0x61, 0xce, 0x06, 0xad, 0x6b, 0xfb, 0xca, 0x5b, 0x1e, 0x72, 0x3c, 0xbb, 0x3c, 0x7c, 0xdc, 0xf5, 0xd7, 0x05, 0xc5, 0xc6, 0xa6, 0x72, 0x05, 0x82, 0x07, 0xe4, 0xa0, 0xd8, 0x2c, 0xbc, 0xf1, 0x18, 0x20, 0x86, 0xec, 0x66, 0x5f, 0xec, 0x3d, 0x10, 0x79, 0x1e, 0xb6, 0xbd, 0x75, 0x45, 0x22, 0x65, 0x5c, 0x5c, 0x2b, 0x27, 0x50, 0x82, 0xcc, 0x02, 0x7f, 0x21, 0x5b, 0x3e, 0x23, 0x15, 0xd0, 0xa4, 0xb9, 0x28, 0x10, 0x21, 0xce, 0x34, 0xac, 0x12, 0x5f, 0x7b, 0xb0, 0xd6, 0x7d, 0x79, 0xfd, 0x81, 0x3f, 0x12, 0xc4, 0xc8, 0xf3, 0x02, 0x93, 0x68, 0x26, 0x7b, 0x1b, 0x0d, 0x29, 0xd9, 0xeb, 0xfa, 0x06, 0xd2, 0xed, 0x71, 0x5b, 0x21, 0xc7, 0xb1, 0x26, 0x08, 0x93, 0xba, 0x7d, 0x61, 0x22, 0x4c, 0x2b, 0x91, 0x5f, 0x9a, 0x33, 0xda, 0x0b, 0x76, 0x93, 0x04, 0x47 };
const unsigned int DRAGON_BIN_SIZE = 365;
#endif // DRAGON_DATA_H
File added
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dshlib.h"
/* DO NOT EDIT
* main() logic moved to exec_local_cmd_loop() in dshlib.c
*/
int main(){
int rc = exec_local_cmd_loop();
printf("cmd loop returned %d\n", rc);
}
\ No newline at end of file
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <errno.h>
#include "dshlib.h"
/*
* Implement your exec_local_cmd_loop 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.
*
* 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
* ERR_MEMORY dynamic memory management failure
*
* errors returned
* OK No error
* ERR_MEMORY Dynamic memory management failure
* WARN_NO_CMDS No commands parsed
* ERR_TOO_MANY_COMMANDS too many pipes used
*
* console messages
* CMD_WARN_NO_CMD print on WARN_NO_CMDS
* CMD_ERR_PIPE_LIMIT print on ERR_TOO_MANY_COMMANDS
* CMD_ERR_EXECUTE print on execution failure of external command
*
* Standard Library Functions You Might Want To Consider Using (assignment 1+)
* malloc(), free(), strlen(), fgets(), strcspn(), printf()
*
* Standard Library Functions You Might Want To Consider Using (assignment 2+)
* fork(), execvp(), exit(), chdir()
*/
int alloc_cmd_buff(cmd_buff_t *cmd_buff) {
cmd_buff->_cmd_buffer = (char *)malloc(SH_CMD_MAX * sizeof(char));
if (!cmd_buff->_cmd_buffer) {
return ERR_MEMORY;
}
memset(cmd_buff->_cmd_buffer, 0, SH_CMD_MAX);
return OK;
}
int free_cmd_buff(cmd_buff_t *cmd_buff) {
if (cmd_buff->_cmd_buffer) {
free(cmd_buff->_cmd_buffer);
cmd_buff->_cmd_buffer = NULL;
}
return OK;
}
int clear_cmd_buff(cmd_buff_t *cmd_buff) {
memset(cmd_buff, 0, sizeof(cmd_buff_t));
return OK;
}
int build_cmd_buff(char *cmd_line, cmd_buff_t *cmd_buff) {
clear_cmd_buff(cmd_buff);
int i = 0;
char *cmd_start = cmd_line;
char *token_start = NULL;
bool in_quotes = false;
while (*cmd_start) {
// Detect start of quoted argument
if (*cmd_start == '\"' && !in_quotes) {
in_quotes = true;
token_start = ++cmd_start;
}
// Detect end of quoted argument
else if (*cmd_start == '\"' && in_quotes) {
in_quotes = false;
*cmd_start = '\0';
cmd_buff->argv[i++] = token_start;
}
// Handle normal argument (non-space outside quotes)
else if (!in_quotes && (*cmd_start != ' ' && *cmd_start != '\t')) {
token_start = cmd_start;
while (*cmd_start != ' ' && *cmd_start != '\t' && *cmd_start != '\0') {
cmd_start++;
}
if (*cmd_start != '\0') {
*cmd_start = '\0';
cmd_start++;
}
cmd_buff->argv[i++] = token_start;
}
else {
cmd_start++;
}
}
cmd_buff->argv[i] = NULL;
cmd_buff->argc = i;
if (i > 0) {
return OK;
} else {
return WARN_NO_CMDS;
}
}
Built_In_Cmds match_command(const char *input) {
if (strcmp(input, "exit") == 0) {
return BI_CMD_EXIT;
} else if (strcmp(input, "cd") == 0) {
return BI_CMD_CD;
} else if (strcmp(input, "dragon") == 0) {
return BI_CMD_DRAGON;
}
return BI_NOT_BI;
}
Built_In_Cmds exec_built_in_cmd(cmd_buff_t *cmd) {
Built_In_Cmds cmd_type = match_command(cmd->argv[0]);
if (cmd_type == BI_CMD_EXIT) {
return BI_CMD_EXIT;
}
if (cmd_type == BI_CMD_CD) {
if (cmd->argc > 1) {
if (chdir(cmd->argv[1]) != 0) {
fprintf(stderr, "cd: %s: No such file or directory\n", cmd->argv[1]);
return ERR_EXEC_CMD;
}
}
return BI_EXECUTED;
}
if (cmd_type == BI_CMD_DRAGON) {
print_dragon();
return BI_EXECUTED;
}
return BI_NOT_BI;
}
int exec_cmd(cmd_buff_t *cmd) {
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return ERR_EXEC_CMD;
} else if (pid == 0) {
int fd_in = -1, fd_out = -1;
int new_argc = 0;
char *new_argv[CMD_ARGV_MAX];
for (int i = 0; i < cmd->argc; i++) {
if (strcmp(cmd->argv[i], "<") == 0) {
if (cmd->argv[i + 1] == NULL) {
fprintf(stderr, "error: missing input file for redirection\n");
exit(ERR_EXEC_CMD);
}
fd_in = open(cmd->argv[i + 1], O_RDONLY);
if (fd_in == -1) {
perror("open input file");
exit(ERR_EXEC_CMD);
}
dup2(fd_in, STDIN_FILENO);
close(fd_in);
i++;
}
else if (strcmp(cmd->argv[i], ">") == 0) {
if (cmd->argv[i + 1] == NULL) {
fprintf(stderr, "error: missing output file for redirection\n");
exit(ERR_EXEC_CMD);
}
fd_out = open(cmd->argv[i + 1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd_out == -1) {
perror("open output file");
exit(ERR_EXEC_CMD);
}
dup2(fd_out, STDOUT_FILENO);
close(fd_out);
i++;
}
else if (strcmp(cmd->argv[i], ">>") == 0) {
if (cmd->argv[i + 1] == NULL) {
fprintf(stderr, "error: missing output file for append\n");
exit(ERR_EXEC_CMD);
}
fd_out = open(cmd->argv[i + 1], O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd_out == -1) {
perror("open output file");
exit(ERR_EXEC_CMD);
}
dup2(fd_out, STDOUT_FILENO);
close(fd_out);
i++;
}
else {
new_argv[new_argc++] = cmd->argv[i];
}
}
new_argv[new_argc] = NULL; // Null-terminate cleaned argument list
execvp(new_argv[0], new_argv);
perror("execvp");
exit(ERR_EXEC_CMD);
} else { // Parent process
int status;
waitpid(pid, &status, 0);
return (WIFEXITED(status)) ? WEXITSTATUS(status) : ERR_EXEC_CMD;
}
}
int build_cmd_list(char *cmd_line, command_list_t *clist) {
clear_cmd_buff((cmd_buff_t *)clist);
char *token = strtok(cmd_line, PIPE_STRING);
int count = 0;
while (token != NULL) {
if (count >= CMD_MAX) {
printf(CMD_ERR_PIPE_LIMIT, CMD_MAX);
return ERR_TOO_MANY_COMMANDS;
}
build_cmd_buff(token, &clist->commands[count]);
count++;
token = strtok(NULL, PIPE_STRING);
}
clist->num = count;
return (count > 0) ? OK : WARN_NO_CMDS;
}
int execute_pipeline(command_list_t *clist) {
if (clist->num < 1) return WARN_NO_CMDS;
int pipes[CMD_MAX - 1][2];
pid_t pids[CMD_MAX];
// Create pipes
for (int i = 0; i < clist->num - 1; i++) {
if (pipe(pipes[i]) == -1) {
perror("pipe");
return ERR_EXEC_CMD;
}
}
// Process input redirection for the first command before forking
int fd_in = -1;
int first_cmd_argc = 0;
char *first_cmd_argv[CMD_ARGV_MAX];
for (int j = 0; j < clist->commands[0].argc; j++) {
if (strcmp(clist->commands[0].argv[j], "<") == 0) {
if (clist->commands[0].argv[j + 1] == NULL) {
fprintf(stderr, "error: missing input file\n");
return ERR_EXEC_CMD;
}
fd_in = open(clist->commands[0].argv[j + 1], O_RDONLY);
if (fd_in == -1) {
perror("open input file");
return ERR_EXEC_CMD;
}
j++; // Skip file name argument
} else {
first_cmd_argv[first_cmd_argc++] = clist->commands[0].argv[j]; // Copy valid arguments
}
}
first_cmd_argv[first_cmd_argc] = NULL;
// Fork processes for each command
for (int i = 0; i < clist->num; i++) {
pids[i] = fork();
if (pids[i] == -1) {
perror("fork");
return ERR_EXEC_CMD;
}
if (pids[i] == 0) { // Child process
if (i == 0 && fd_in != -1) {
dup2(fd_in, STDIN_FILENO);
close(fd_in);
}
if (i > 0) {
dup2(pipes[i - 1][0], STDIN_FILENO);
}
if (i < clist->num - 1) {
dup2(pipes[i][1], STDOUT_FILENO);
}
// Close all pipes in child
for (int j = 0; j < clist->num - 1; j++) {
close(pipes[j][0]);
close(pipes[j][1]);
}
if (i == 0) {
execvp(first_cmd_argv[0], first_cmd_argv);
} else {
execvp(clist->commands[i].argv[0], clist->commands[i].argv);
}
perror("execvp");
exit(ERR_EXEC_CMD);
}
}
// Close all pipes in parent
for (int i = 0; i < clist->num - 1; i++) {
close(pipes[i][0]);
close(pipes[i][1]);
}
if (fd_in != -1) close(fd_in);
int status;
for (int i = 0; i < clist->num; i++) {
waitpid(pids[i], &status, 0);
}
return OK;
}
int exec_local_cmd_loop() {
char cmd_line[SH_CMD_MAX];
command_list_t clist;
while (1) {
printf("%s", SH_PROMPT);
if (fgets(cmd_line, sizeof(cmd_line), stdin) == NULL) {
printf("\n");
break;
}
cmd_line[strcspn(cmd_line, "\n")] = '\0';
if (build_cmd_list(cmd_line, &clist) == WARN_NO_CMDS) {
printf(CMD_WARN_NO_CMD);
continue;
}
// If only one command, execute it normally
if (clist.num == 1) {
Built_In_Cmds result = exec_built_in_cmd(&clist.commands[0]);
if (result == BI_CMD_EXIT) {
return OK_EXIT;
} else if (result == BI_NOT_BI) {
exec_cmd(&clist.commands[0]);
}
} else {
execute_pipeline(&clist); // pipeline
}
}
return OK;
}
#ifndef __DSHLIB_H__
#define __DSHLIB_H__
//Constants for command structure sizes
#define EXE_MAX 64
#define ARG_MAX 256
#define CMD_MAX 8
#define CMD_ARGV_MAX (CMD_MAX + 1)
// 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 cmd_buff
{
int argc;
char *argv[CMD_ARGV_MAX];
char *_cmd_buffer;
} cmd_buff_t;
/* WIP - Move to next assignment
#define N_ARG_MAX 15 //MAX number of args for a command
typedef struct command{
char exe [EXE_MAX];
char args[ARG_MAX];
int argc;
char *argv[N_ARG_MAX + 1]; //last argv[LAST] must be \0
}command_t;
*/
typedef struct command_list{
int num;
cmd_buff_t commands[CMD_MAX];
}command_list_t;
//Special character #defines
#define SPACE_CHAR ' '
#define PIPE_CHAR '|'
#define PIPE_STRING "|"
#define SH_PROMPT "dsh3> "
#define EXIT_CMD "exit"
#define EXIT_SC 99
//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
#define ERR_CMD_ARGS_BAD -4 //for extra credit
#define ERR_MEMORY -5
#define ERR_EXEC_CMD -6
#define OK_EXIT -7
//prototypes
int alloc_cmd_buff(cmd_buff_t *cmd_buff);
int free_cmd_buff(cmd_buff_t *cmd_buff);
int clear_cmd_buff(cmd_buff_t *cmd_buff);
int build_cmd_buff(char *cmd_line, cmd_buff_t *cmd_buff);
int close_cmd_buff(cmd_buff_t *cmd_buff);
int build_cmd_list(char *cmd_line, command_list_t *clist);
int free_cmd_list(command_list_t *cmd_lst);
void print_dragon();
//built in command stuff
typedef enum {
BI_CMD_EXIT,
BI_CMD_DRAGON,
BI_CMD_CD,
BI_NOT_BI,
BI_EXECUTED,
} Built_In_Cmds;
Built_In_Cmds match_command(const char *input);
Built_In_Cmds exec_built_in_cmd(cmd_buff_t *cmd);
//main execution context
int exec_local_cmd_loop();
int exec_cmd(cmd_buff_t *cmd);
int execute_pipeline(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
# Compiler settings
CC = gcc
CFLAGS = -Wall -Wextra -g
LDFLAGS = -lz
# 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) $(LDFLAGS)
# Clean up build files
clean:
rm -f $(TARGET)
test:
bats $(wildcard ./bats/*.sh)
valgrind:
echo "pwd\nexit" | valgrind --leak-check=full --show-leak-kinds=all --error-exitcode=1 ./$(TARGET)
echo "pwd\nexit" | valgrind --tool=helgrind --error-exitcode=1 ./$(TARGET)
# Phony targets
.PHONY: all clean test
\ No newline at end of file
1. Your shell forks multiple child processes when executing piped commands. How does your implementation ensure that all child processes complete before the shell continues accepting user input? What would happen if you forgot to call waitpid() on all child processes?
> When executing piped commands, my implementation ensures that all child processes complete before the shell continues by using `waitpid()` in a loop for each forked child process.
> - Each command in the pipeline is executed in a separate child process created using `fork()`.
> - The parent process waits for each child using `waitpid(pid, &status, 0)`, ensuring that all child processes complete before the shell resumes accepting input.
> - `waitpid()` make sure that the shell does not continue execution before all commands in the pipeline are finished.
> What happens if I forget `waitpid()`?
> - If `waitpid()` is not called for each child, completed child processes still exist in the system and are not ended.
> - The shell would return to the prompt while background child processes are still running.
> - Resource leaks.
2. The dup2() function is used to redirect input and output file descriptors. Explain why it is necessary to close unused pipe ends after calling dup2(). What could go wrong if you leave pipes open?
> Closing unused pipe ends is essential to prevent issues such as:
> - If a process never closes the unused end, the pipe remain open infinitely.
> - If the write end of a pipe remains open after redirection, the process reading from the pipe will never receive EOF, causing it to wait forever.
3. Your shell recognizes built-in commands (cd, exit, dragon). Unlike external commands, built-in commands do not require execvp(). Why is cd implemented as a built-in rather than an external command? What challenges would arise if cd were implemented as an external process?
> - `cd` modifies the shell's working directory using `chdir()`. Since each child process has its own copy of the shell's environment, running `cd` as an external command would only change the directory for that child process, not the main shell.
> - Challenge: The shell would need to track and manually apply directory changes after each `cd` execution.
4. Currently, your shell supports a fixed number of piped commands (CMD_MAX). How would you modify your implementation to allow an arbitrary number of piped commands while still handling memory allocation efficiently? What trade-offs would you need to consider?
> Dynamic memory allocation would be needed for storing unlimited pipes.
> Instead of using a fixed-size array, use `realloc()` to expand memory as new piped commands are parsed.
> Trade off:
> - Increases memory usage.
> - Adds complexity to the shell.
> - Exceeding file descriptor limit.
\ No newline at end of file
# Assignment: Custom Shell Part 3 - Pipes
This week we will build on our `dsh` Drexel Shell by implementing pipes. In the first shell assignment we approached this subject by splitting lines of input by the pipe `|` and printing out each separate command parsed between the pipes. In the second assignment we set the pipe splitting logic aside and implemented _execution_ of single commands.
This week we'll bring these concepts together by implementing pipelined execution of multiple commands!
# Reuse Prior Work!
The `dsh` assignments are meant to be additive. This week you'll need to use code you wrote in the first two shell assignments. Be sure to re-use your existing code, and refactor it to meet the requirements of this assignment.
# Pipes
This week you'll need to use a couple new important syscalls - `pipe()` and `dup2()`.
The `pipe()` command creates a 1-way communication path that is implemented with two file descriptions. Conceptually it looks like this:
```txt
process-1-output --write--> pipe[fd1]:pipe[fd0] --read--> process-2-input
```
How do the pipes get "connected" between the processes? That's where `dup2()` comes in.
> Tip: pipes should be created and connected inside a `fork()`; you've already used `fork/execvp` to implement a single command. This time you'll need to do that in a loop, because each command should get it's own `fork/execvp`. So, you'll need to handle `pipe()` and `dup2()` _inside_ each child's fork.
Think of `dup2()` as sort of patching or redirection. The function signature is:
`dup2(source_fd, target_fd)`
Remember that each forked child has it's own process space and set of file descriptors, to include `STDIN_FILENO` and `STDOUT_FILENO`. So, inside each child process, you could use dup2 to _replace_ the child's STDIN and STDOUT with pipe file descriptors instead.
**Preventing Descriptor Leaks**
When you use `dup2()`, it _copies_ the source FD onto the target, effectively replacing the target. The source is no longer used, and can be closed. If you don't close the original pipes after copying with `dup2()`, you have introduced a **descriptor leak**; this could cause your program to run out of available file descriptors.
# Multiple Children / Waitpid
Since you must create multiple forks to handle piped commands, be sure to wait on all of them with `waitpid()`, which can be used to wait for a specific process id. _(Hint: you'll need to save the pid of each process you fork)._
# Assignment Details
### Step 1 - Review [./starter/dshlib.h](./starter/dshlib.h)
The file [./starter/dshlib.h](./starter/dshlib.h) contains some useful definitions and types. Review the available resources in this file before you start coding - these are intended to make your work easier and more robust!
### Step 2 - Re-implement Your Main Loop and Parsing Code in exec_local_cmd_loop() to parse multiple commands by pipe [./starter/dshlib.c](./starter/dshlib.c)
This should mostly be a refactoring, copy/paste exercise to merge your solutions from the first two shell assignments. You need to combine your pipe tokenizing solution with loading up `cmd_buff_t` ultimately into a `command_list_t`.
### Step 3 - Implement pipelined execution of the parsed commands [./starter/dshlib.c](./starter/dshlib.c)
The first part of this is a refactoring problem - instead of just one `fork/exec`, you'll need to do that in a loop and keep track of the child pids and child exit statuses.
The second part is implementing pipe logic. The section above named "Pipes" contains everything you really need to know! Also, check out demo code from this week's lecture [5-pipe-handling](https://github.com/drexel-systems/SysProg-Class/tree/main/demos/process-thread/5-pipe-handling).
### Step 4 - Create BATS Tests
You should now be familiar with authoring your own [bash-based BATS unit tests](https://bats-core.readthedocs.io/en/stable/tutorial.html#your-first-test) from the prior assignment.
Same as last week, you have an "assignment-tests.sh" file that we provide and you cannot change, and a "student_tests.sh" file that **you need to add your own tests to**:
- your-workspace-folder/
- bats/assignement_tests.sh
- bats/student_tests.sh
**This week we expect YOU to come up with the majority of the test cases! If you have trouble, look at the tests we provided from prior weeks**
**Be sure to run `make test` and verify your tests pass before submitting assignments.**
### Step 5 - Answer Questions
Answer the questions located in [./questions.md](./questions.md).
### Sample Run with Sample Output
The below shows a sample run executing multiple commands and the expected program output:
```bash
./dsh
dsh3> ls | grep ".c"
dragon.c
dsh_cli.c
dshlib.c
dsh3> exit
exiting...
cmd loop returned 0
```
### Extra Credit: +10
Last week you should have learned about redirection (it was part of the assignment's research question). Once you've implemented pipes for this assignment, redirection is a natural next step.
**Requirements**
- parse `<` and `>` during command buffer creation; you'll need to parse and track these on `cmd_buff_t`
- modify command execution to use `dup2()` in a similar way as you did for pipes; you can copy the in and out fd's specified by the user on to STDIN or STDOUT of the child's forked process
Example run:
```bash
./dsh
dsh3> echo "hello, class" > out.txt
dsh3> cat out.txt
hello, class
```
### Extra Credit++: +5
Extend the first extra credit to implement `>>`. This is the same as `>`, except the target fd is in append mode.
Example run:
```bash
./dsh
dsh3> echo "hello, class" > out.txt
dsh3> cat out.txt
hello, class
dsh3> echo "this is line 2" >> out.txt
dsh3> cat out.txt
hello, class
this is line 2
dsh3>
```
#### Grading Rubric
- 50 points: Correct implementation of required functionality
- 5 points: Code quality (how easy is your solution to follow)
- 10 points: Answering the written questions: [questions.md](./questions.md)
- 10 points: Quality and breadth of BATS unit tests
- 10 points: [EXTRA CREDIT] handle < and > redirection
- 5 points: [EXTRA CREDIT++] handle >> append redirection
Total points achievable is 90/75.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment