-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
67 lines (55 loc) · 1.33 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
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
// arglist - a list of char* arguments (words) provided by the user
// it contains count+1 items, where the last item (arglist[count]) and *only* the last is NULL
// RETURNS - 1 if should continue, 0 otherwise
int process_arglist(int count, char** arglist);
// prepare and finalize calls for initialization and destruction of anything required
int prepare(void);
int finalize(void);
int main(void)
{
if (prepare() != 0)
exit(1);
while (1)
{
char** arglist = NULL;
char* line = NULL;
size_t size;
int count = 0;
if (getline(&line, &size, stdin) == -1) {
free(line);
break;
}
arglist = (char**) malloc(sizeof(char*));
if (arglist == NULL) {
printf("malloc failed: %s\n", strerror(errno));
exit(1);
}
arglist[0] = strtok(line, " \t\n");
while (arglist[count] != NULL) {
++count;
arglist = (char**) realloc(arglist, sizeof(char*) * (count + 1));
if (arglist == NULL) {
printf("realloc failed: %s\n", strerror(errno));
exit(1);
}
arglist[count] = strtok(NULL, " \t\n");
}
if (count != 0) {
if (!process_arglist(count, arglist)) {
free(line);
free(arglist);
break;
}
}
free(line);
free(arglist);
}
if (finalize() != 0)
exit(1);
return 0;
}