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
|
#include "shell.h"
static void cleanwhitespaces(char *line);
static int parseline(char *line, char **v);
static void
cleanwhitespaces(char *line)
{
char *i;
for (i = line; *i != 0; i++)
if (*i == '\t' || *i == '\n')
*i = ' ';
}
/* This function assumes that **v is large enough */
static int
parseline(char *line, char **v)
{
char *t;
int n = 0;
cleanwhitespaces(line);
for (t = strtok(line, " "); t != NULL; t = strtok(NULL, " "))
strcpy(v[n++], t);
return n;
}
void
exec_args(int c, char **v)
{
int i;
Command *cmd = NULL;
CommandArgs *args;
for (i = 0; i < NCOMMANDS; i++)
if (commands[i] != NULL && !strcmp(v[0], commands[i]->name))
cmd = commands[i];
if (cmd == NULL) {
fprintf(stderr, "%s: command not found\n", v[0]);
return;
}
args = cmd->parse_args(c-1, &v[1]);
if (!args->success) {
fprintf(stderr, "usage: %s\n", cmd->usage);
return;
}
cmd->exec(args);
free_args(args);
}
void
launch()
{
int i, shell_argc;
char line[MAXLINELEN], **shell_argv;
shell_argv = malloc(MAXNTOKENS * sizeof(char *));
for (i = 0; i < MAXNTOKENS; i++)
shell_argv[i] = malloc((MAXTOKENLEN+1) * sizeof(char));
fprintf(stderr, "Welcome to Nissy "VERSION".\n");
fprintf(stderr, "Type 'help' for a list.\n");
while (true) {
fprintf(stderr, "nissy-# ");
if (fgets(line, MAXLINELEN, stdin) == NULL)
break;
shell_argc = parseline(line, shell_argv);
if (shell_argc > 0)
exec_args(shell_argc, shell_argv);
}
for (i = 0; i < MAXNTOKENS; i++)
free(shell_argv[i]);
free(shell_argv);
}
int
main(int argc, char *argv[])
{
if (argc > 1)
exec_args(argc-1, &argv[1]);
else
launch();
return 0;
}
|