-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsh.c
89 lines (72 loc) · 1.28 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
/*
* Shell for OS-161
* Usage: Testing system calls for Assignment-2
*/
#ifdef HOST
#include "hostcompat.h"
#endif
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 255
#define MAX_ARGS 255
int
get_line(char *line)
{
int pos;
int ch;
pos = 0;
while (1) {
ch = getchar();
if (ch == EOF) break;
putchar(ch);
if (ch == '\n') { break; }
line[pos++] = ch;
if (pos == MAX_LINE_LENGTH - 1) {
putchar('\n');
break;
}
}
line[pos] = '\0';
return 0;
}
int
main(int argc, char *argv[])
{
#ifdef HOST
hostcompat_init(argc, argv);
#endif
(void)argc;
(void)argv;
char line[MAX_LINE_LENGTH];
int result;
pid_t child_pid;
int status;
char *tokens[MAX_ARGS+1];
while (1) {
printf("os161-sh$ ");
result = get_line(line);
if (strcmp(line, "exit") == 0) break;
if (strlen(line) == 0) continue;
tokens[0] = (char *)line;
int count = 0;
char *ptr;
for (ptr = line; *ptr != (char)NULL; ptr++) {
if (*ptr == ' ') {
*ptr = (char)NULL;
tokens[++count] = ptr + 1;
}
}
tokens[count+1] = NULL;
child_pid = fork();
if (child_pid == 0) {
execv(line, tokens);
printf("%s: execv failed\n", tokens[0]);
exit(1); // TODO
} else {
waitpid(child_pid, &status, 0);
}
}
exit(0);
}