-
Notifications
You must be signed in to change notification settings - Fork 0
/
shell.c
115 lines (94 loc) · 2.77 KB
/
shell.c
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
#include <aio.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#define PROMPT "$ "
#define DELIMITER " \t\r\n\a"
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#define strdup(s) (strcpy(malloc(strlen(s) + 1), s))
static char **shell_split(char *string, char *delimeter);
static char *shell_read_line(FILE *file);
int main(void) {
while (true) {
printf("%s", PROMPT);
char *line = shell_read_line(stdin);
if (line == NULL) {
return EXIT_SUCCESS;
}
// Execute the program.
pid_t pid = fork();
if (pid < 0) {
eprintf("failed to fork\n");
return EXIT_FAILURE;
} else if (pid == 0) {
char **args = shell_split(line, DELIMITER);
execvp(args[0], args);
// This will only be reached if EXECVP fails above.
perror(NULL);
} else {
wait(NULL);
}
}
return EXIT_SUCCESS;
}
/**
* Split STRING on DELIMETER.
*
* For example:
*
* >>> shell_split("Hello, world!", " ")
* {"Hello,", "world!"}
*/
static char **shell_split(char *string, char *delimeter) {
// If a string literal is passed in, STRTOK would have a segmentation fault
// when it attempts to modify the string -- therefore we need a copy of the
// string.
char *copy = strdup(string);
// Allocate space for 32 strings to start of with, but we'll change this
// size dynamically depending on what's needed.
size_t size = 32;
char **tokens = malloc(size * sizeof(char *));
char *token = strtok(copy, delimeter);
tokens[0] = token;
for (size_t position = 1;; position += 1) {
if (position > size) {
if (realloc(tokens, size * 2 * sizeof(char)) == NULL) {
free(tokens);
return NULL;
}
size *= 2;
}
char *token = strtok(NULL, delimeter);
tokens[position] = token;
if (token == NULL) {
break;
}
}
return tokens;
}
/**
* Read a single line from FILE, dynamically allocating the result to be as long
* as necessary.
*/
static char *shell_read_line(FILE *file) {
size_t size = 32;
char *line = malloc(size * sizeof(char));
int current;
for (size_t position = 0; (current = fgetc(file)) != EOF; position += 1) {
if (position > size) {
if (realloc(line, size * 2 * sizeof(char)) == NULL) {
free(line);
return NULL;
}
size *= 2;
}
line[position] = (current == '\n' || current == EOF) ? '\0' : current;
if (current == '\n' || current == EOF) {
return line;
}
}
return line;
}