-
Notifications
You must be signed in to change notification settings - Fork 14
/
sh_t.c
122 lines (107 loc) · 2.52 KB
/
sh_t.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
/**
@brief Launch a program and wait for it to terminate.
@param args Null terminated list of arguments (including program).
@return Always returns 1, to continue execution.
*/
int sh_launch(char **args) { /* your code here */ }
/**
@brief Execute shell built-in or launch program.
@param args Null terminated list of arguments.
@return 1 if the shell should continue running, 0 if it should terminate
*/
int sh_execute(char **args)
{
int i;
if (args[0] == NULL) {
return 1; // An empty command was entered.
}
return sh_launch(args); // launch
}
/**
@brief Read a line of input from stdin.
@return The line from stdin.
*/
char *sh_read_line(void)
{
char *line = NULL;
ssize_t bufsize = 0; // have getline allocate a buffer for us
if (getline(&line, &bufsize, stdin) == -1) {
if (feof(stdin)) {
exit(EXIT_SUCCESS); // We recieved an EOF
} else {
perror("sh: readline");
exit(EXIT_FAILURE);
}
}
return line;
}
#define SH_TOK_BUFSIZE 64
#define SH_TOK_DELIM " \t\r\n\a"
/**
@brief Split a line into tokens (very naively).
@param line The line.
@return Null-terminated array of tokens.
*/
char **sh_split_line(char *line)
{
int bufsize = SH_TOK_BUFSIZE, position = 0;
char **tokens = malloc(bufsize * sizeof(char *));
char *token, **tokens_backup;
if (!tokens) {
fprintf(stderr, "sh: allocation error\n");
exit(EXIT_FAILURE);
}
token = strtok(line, SH_TOK_DELIM);
while (token != NULL) {
tokens[position] = token;
position++;
if (position >= bufsize) {
bufsize += SH_TOK_BUFSIZE;
tokens_backup = tokens;
tokens = realloc(tokens, bufsize * sizeof(char *));
if (!tokens) {
free(tokens_backup);
fprintf(stderr, "sh: allocation error\n");
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, SH_TOK_DELIM);
}
tokens[position] = NULL;
return tokens;
}
/**
@brief Loop getting input and executing it.
*/
void sh_loop(void)
{
char *line;
char **args;
int status;
do {
printf("238P$ ");
line = sh_read_line();
args = sh_split_line(line);
status = sh_execute(args);
free(line);
free(args);
} while (status);
}
/**
@brief Main entry point.
@param argc Argument count.
@param argv Argument vector.
@return status code
*/
int main(int argc, char **argv)
{
// Run command loop.
sh_loop();
return EXIT_SUCCESS;
}