summaryrefslogtreecommitdiffstats
path: root/02_exercise/shell.c
blob: e21957de8aa0d03b9d7460e7ce99b2556b92bf20 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#include <wait.h>
#include <errno.h>

#include "array.h"
#include "process.h"
#include "prompt_utils.h"

void handle(int sig) {
    /* Do nothing. */
}

int main(void) {
    setvbuf(stderr, NULL, _IONBF, 0);
    setvbuf(stdout, NULL, _IONBF, 0);

    struct sigaction handler;
    handler.sa_handler = handle;
    sigemptyset(&handler.sa_mask);
    handler.sa_flags = 0;

    printf("Welcome! Available built-ins are:\n"
           "cd: `cd <path>` - if no path is given, return to the current dir\n"
           "wait: `wait pid1 ... pidN` - wait on the processes and report their exit conditions\n"
           "fg: `fg pid` - pulls a process from the background back in the foreground (#TODO)\n"
           "\n"
           "You can put processes in the background using the unary `&` for new processes, and using CTRL-Z (#TODO) for already running ones\n"
           "With `|` you can pipe the output from one process to the input of another\n"
    );

    char const *const original_wd = get_current_dir_name();
    char const *prompt = relative_path(original_wd, original_wd);
    bool done = false;
    while (!done) {
        char *line = NULL;
        size_t cap = 0;
        __ssize_t length = 0;

        printf("%s > ", prompt);
        if ((length = getline(&line, &cap, stdin)) < 0) {
            fprintf(stderr, "Failed to read from STDIN");
            fflush(stderr);
            exit(-1);
        }

        if (strspn(line, " \n\t") == strlen(line)) {
            // skip empty lines - empty being just spaces or tabs
            continue;
        }
        line[length - 1] = '\0'; // cut the line feed

        process *processes = NULL;
        parse_line(line, &processes);

        if (strcmp(processes[0].argv[0], "cd") == 0) {
            if (arrayLen(processes) != 1) {
                perror("Can't chain cd with other processes");
            }

            int ret;
            switch(arrayLen(processes[0].argv)) {
                case 3:
                    ret = chdir(processes[0].argv[1]);
                    break;
                case 2:
                    ret = chdir(original_wd);
                    break;
                default:
                    fprintf(stderr, "usage: cd <path>\n");
                    fflush(stderr);
                    ret = -1;
            }

            if (ret)
                printf("[%i] ", ret);

            free((void *)prompt);
            char const *current_wd = get_current_dir_name();
            prompt = relative_path(original_wd, current_wd);
            free((void *)current_wd);
        } else if (strcmp(processes[0].argv[0], "exit") == 0) {
            done = true;
        } else if (strcmp(processes[0].argv[0], "wait") == 0) {
            bool error = false;
            pid_t *pids;
            arrayInit(pids);
            size_t i = 1;
            while (!error && processes[0].argv[i] != NULL) {
                char *end;
                pid_t tmp = strtol(processes[0].argv[i], &end, 10);
                if (*end != '\0') {
                    fprintf(stderr, "Not a valid pid: %s", processes[0].argv[i]);
                    error = true;
                    break;
                }
                arrayPush(pids) = tmp;
                ++i;
            }

            if (!error) {
                while (!arrayIsEmpty(pids)) {
                    int status;
                    pid_t current_pid = arrayPop(pids);
                    printf("Waiting for %ld...\n", (long) current_pid);
                    // install signal handler without SA_RESTART, so waitpid gets interrupted
                    sigaction(SIGINT, &handler, NULL);
                    if (waitpid(current_pid, &status, WUNTRACED) < 0) {
                        if (EINTR == errno) {
                            // cancelled by ctrl-c
                        } else {
                            perror("Could not wait on process");
                        }
                    } else {
                        printf("[%i] TERMINATED\n", current_pid);
                        if (WIFEXITED(status)) {
                            printf("[%i] exited normally with status: %i\n", current_pid, WEXITSTATUS(status));
                        } else if (WIFSTOPPED(status)) {
                            printf("[%i] was stopped by signal: %s\n", current_pid, strsignal(WSTOPSIG(status)));
                        } else if (WIFSIGNALED(status)) {
                            printf("[%i] was terminated by signal: %s\n", current_pid, strsignal(WTERMSIG(status)));
                        } else {
                            printf("[%i] exited (not sure why), exit status: %i\n", current_pid, WEXITSTATUS(status));
                        }
                    }
                    signal(SIGINT, SIG_DFL);
                }
            }

            arrayRelease(pids);

        } else {
            for (size_t i = 0; i < arrayLen(processes); ++i) {
                int ret = exec_command(processes[i]);
                if (ret)
                    printf("[%i] ", ret);
            }

        }

        free((void *)line);
        line = NULL;
        cap = 0;
        free_processes(&processes);
    }

    free((void *)original_wd);
    free((void *)prompt);
}