Commit f7775a38 authored by Matthew Burket's avatar Matthew Burket
Browse files

Added background, cd, and moved off of readline

parent bbe80d14
Loading
Loading
Loading
Loading
+29 −6
Original line number Diff line number Diff line
@@ -14,28 +14,51 @@
int main() {
    // Read line examples: https://eli.thegreenplace.net/2016/basics-of-using-the-readline-library/
    int should_run = 1;
    char *readBuff;
    char *readBuff = malloc(sizeof(char) * 5000);
    fprintf(stdout, "Welcome to Burket Shell (bsh)\n");
    fprintf(stdout, "Copyright 2018 Matthew Burket\n");
    fprintf(stdout, "Released under the GPL v3 License\n");
    while (should_run) {
        while ((readBuff = readline("bsh >> ")) != NULL) {
        fprintf(stdout, "bsh # ");
        fgets(readBuff, sizeof(char) * 5000, stdin);
        // Remove the newline from fgets
        strtok(readBuff, "\n");
        //while ((readBuff = readline("bsh >> ")) != 0) {
            if (strlen(readBuff) > 0) {
                add_history(readBuff);
            }

            if (strcmp("exit", readBuff) == TRUE) {
                should_run = 0;
                free(readBuff);
                exit(EXIT_SUCCESS);
            }
            char **tokens = malloc(sizeof(char) * 5000);
            tokenize(readBuff, tokens);
            int numTokens = tokenize(readBuff, tokens);
            char *lastToken = tokens[numTokens-2];
            if (strcmp(tokens[0], "cd") == TRUE) {
                if (tokens[1] == NULL) {
                    fprintf(stderr, "bsh: expected one argument for cd");
                    continue;
                } else {
                    chdir(tokens[1]);
                }
            }

            int runInBackground = 0;
            if (strcmp(lastToken, "&") == TRUE) {
                runInBackground = 1;
                tokens[numTokens-2] = NULL;
            }
            if (fork() == 0) {
                int returnCode = execvp(tokens[0], tokens);
                printf("Return code %d\n", returnCode);
            } else {
                if (runInBackground == 0) {
                    wait(NULL);
                }
            free(readBuff);
            }
            free(tokens);
        }
    //}
}
 No newline at end of file
+2 −2
Original line number Diff line number Diff line
@@ -4,7 +4,7 @@

#include "tokenize.h"

char **tokenize(char *string, char **output) {
int tokenize(char *string, char **output) {
    char *strtok_save;
    char *del = " ";
    output[0] = strtok_r(string, del, &strtok_save);
@@ -15,5 +15,5 @@ char **tokenize(char *string, char **output) {
        output[i] = token;
        i++;
    }
    return output;
    return i;
}
+1 −1
Original line number Diff line number Diff line
@@ -5,5 +5,5 @@
#ifndef COMS352_SHELL_TOKENIZE_H
#define COMS352_SHELL_TOKENIZE_H
#include <string.h>
char **tokenize(char *string, char **output);
int tokenize(char *string, char **output);
#endif //COMS352_SHELL_TOKENIZE_H