-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsh.c
141 lines (105 loc) · 2.14 KB
/
sh.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
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
#include <stdio.h>
#include <stdarg.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#define MAX_COMMAND_SIZE 256
#define MAX_PARAMETERS 128
//#define DEBUG
extern void *_main(void *);
extern int _arp_cache(int, const char **);
extern int _ifconf(int, const char **);
extern int echo_init(int, const char **);
extern int netstat(int, const char **);
extern int http_init(int, const char **);
struct cmd {
char *name;
int (*func)(int, const char **);
};
#ifdef SHELL
int _cmd_func(int argc, const char **arg)
{
int i;
static struct cmd cmds[] = {{"arp", _arp_cache},
{"ifconfig", _ifconf},
{"netstat", netstat},
{"http", http_init},
{"echo", echo_init}};
int count = sizeof(cmds) / sizeof(cmds[(0)]);
for (i = 0; i < count; i++) {
if (!(strncmp(arg[0], cmds[i].name, strlen(arg[0])))) {
return cmds[i].func(argc, arg);
}
}
return -1;
}
int check_command(char *cmd)
{
int argc;
int ret;
const char *arg[MAX_PARAMETERS] = {};
char *tmp;
#ifdef DEBUG
printf("%s\n", cmd);
#endif
argc = 0;
arg[argc] = strtok(cmd, " ");
while (arg[argc] != (NULL)) {
arg[++argc] = strtok(NULL, " ");
if (arg[argc] == (NULL)) {
argc--;
break;
}
}
if (argc == 0 && arg[0] == (NULL)) {
return 0;
}
argc++;
ret = _cmd_func(argc, arg);
if (ret < 0) {
printf("command not found\n");
}
return 0;
}
int _char_in(char ch)
{
static char cmd[MAX_COMMAND_SIZE];
static int index = 0;
switch (ch) {
case 'a' ... 'z':
case 'A' ... 'Z':
case 0 ... 9:
case ' ':
cmd[index++] = ch;
// putchar(ch);
break;
case '\r':
case '\n':
cmd[index++] = '\0';
check_command(cmd);
index = 0;
printf("m-shell> ");
// memset(cmd, '\0', MAX_COMMAND_SIZE - 1);
break;
}
return 0;
}
#endif /* SHELL */
int main(int argc, char **args)
{
int ret;
char ch;
pthread_t threadid;
ret = pthread_create(&threadid, NULL, _main, NULL);
if (ret != 0) {
perror("error pthread_create");
exit(-1);
}
while (1) {
#ifdef SHELL
ch = getchar();
_char_in(ch);
#endif
}
return 0;
}