-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.c
More file actions
367 lines (312 loc) · 7.28 KB
/
shell.c
File metadata and controls
367 lines (312 loc) · 7.28 KB
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
ls | cat -n | cat -n | cat -n | cat -n | cat -n | cat -n
tty
ls -l /proc/self/fd | cat | cat | cat | cat
ps axf | grep tty1
sleep 1 | sleep 1 | sleep 1 | sleep 1 | sleep 1 | sleep 1 | sleep 1 | sleep 1 | sleep 1 | sleep 1
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdbool.h>
#define TOKEN_DELIMITERS = " \t"
bool SHELL_CLOSED = false;
int BACKGROUND_PROCS[256] = { 0 };
int BACKGROUND_PROC_COUNT = 0;
void shell_loop();
void exec_comarg(char* input);
void call_command(char* commandName, char** args, int argc);
bool try_shell_command(char* commandName, char** args, int argc);
void split_into_comargs(char* input, char** outputArr[], int* argc);
void cmd_help();
void cmd_cd(char** args);
int main(int argc, char** argv)
{
printf("This is a tiny shell. call 'help' for more info.\n");
printf("> ");
shell_loop();
return 0;
}
// Main shell loop function
void shell_loop()
{
char* str = NULL;
size_t bufferLen = 0;
size_t nread;
while((nread = getline(&str, &bufferLen, stdin)) != -1 && SHELL_CLOSED == false)
{
char** output = NULL;
int outputSize = 0;
// Check if user just presses 'Enter'
if(strcmp(str, "\n") == 0 || strcmp(str, "\r\n") == 0 || strcmp(str, "") == 0
||strcmp(str, " ") == 0)
{
printf("> ");
continue;
}
// Prepare pipes
int in = dup(0); // stdin
int out = dup(1); // stdout
int fdin;
int fdout;
// Parse the line into an array of comargs (commands + arguments)
split_into_comargs(str, &output, &outputSize);
for(int i = 0; i < outputSize; i++)
{
dup2(fdin, 0);
close(fdin);
if(i == outputSize-1)
{
// Last command
fdout=dup(out);
}
else
{
// Not last command
int fdpipe[2];
pipe(fdpipe);
fdout = fdpipe[1];
fdin = fdpipe[0];
}
dup2(fdout, 1);
close(fdout);
exec_comarg(output[i]);
}
// Go through all background processes, and wait for last process to finish
// Reduce the background process count each time
while(BACKGROUND_PROC_COUNT > 0)
{
for(int i = 0; i < BACKGROUND_PROC_COUNT; i++)
{
int commandStatus = 0;
do
{
if(i == BACKGROUND_PROC_COUNT - 1)
{
waitpid(BACKGROUND_PROCS[i], &commandStatus, WUNTRACED);
}
else
{
waitpid(BACKGROUND_PROCS[i], &commandStatus, WNOHANG);
}
} while (!WIFEXITED(commandStatus) && !WIFSIGNALED(commandStatus));
BACKGROUND_PROCS[i] = 0;
}
BACKGROUND_PROC_COUNT--;
}
BACKGROUND_PROC_COUNT = 0;
// close all pipes, free the memory
// restore stdin and stdout
dup2(in, 0);
dup2(out, 1);
close(in);
close(out);
for(int i = 0; i < outputSize; i++)
{
free(output[i]);
}
free(output);
if(SHELL_CLOSED == true)
{
break;
}
printf("> ");
}
free(str);
}
// A function that generates an array of comargs (command + args) strings, that can be passed to exec_comarg() function
// function expects a pointer to the array of strings, and puts the result into this array
// outputSize is set to the size of output array
void split_into_comargs(char* input, char** outputArr[], int* outputSize)
{
char* token;
char** resultArr = NULL;
token = strtok(input, "|");
while(token != NULL)
{
if((*outputSize) == 0)
{
resultArr = malloc(sizeof(char*));
}
else
{
char** newArr = realloc(resultArr, sizeof(char*) * (*outputSize+1));
if(newArr != NULL)
{
resultArr = newArr;
}
else
{
printf("An error while reallocating memory occurred. %s\n", strerror(errno));
exit(1);
}
if(resultArr == NULL)
{
printf("An error while allocating memory occurred. %s\n", strerror(errno));
exit(1);
}
}
resultArr[(*outputSize)] = malloc(strlen(token)+1);
token[strcspn(token, "\r\n")] = 0;
strcpy(resultArr[(*outputSize)], token);
(*outputSize)++;
token = strtok(NULL, "|");
}
*outputArr = resultArr;
}
// A function that splits given command + args string into tokens, and passes tokenized result into call_command()
void exec_comarg(char* input)
{
char* token;
token = strtok(input, " ");
int argc = 0;
char** args = NULL;
// Tokenize input, get array of strings (args)
while(token != NULL)
{
if(argc == 0)
{
args = malloc(sizeof(char*));
}
else
{
char** newArgs = realloc(args, sizeof(char*)*(argc+1));
if(newArgs != NULL)
{
args = newArgs;
}
else
{
printf("An error while reallocating memory occurred. %s\n", strerror(errno));
exit(1);
}
}
if(args == NULL)
{
printf("An error while allocating memory occurred. %s\n", strerror(errno));
exit(1);
}
// strlen ignores null terminator, so adding + 1 to malloc
args[argc] = malloc(strlen(token) + 1);
token[strcspn(token, "\r\n")] = 0;
strncpy(args[argc], token, strlen(token)+1);
//strcpy(args[argc], token);
argc++;
token = strtok(NULL, " ");
}
// Retrieve commands from parsed args
if(strcmp(args[0], "\n") == 0 || strcmp(args[0], "\0") == 0 || strcmp(args[0], "") == 0)
{
for(int i = 0; i < argc; i++)
{
free(args[i]);
}
free(args);
return;
}
//execvp expects last arg in args to be NULL, make sure we have it..
// execvp expects last arg in args to be NULL, make sure we have it..
char** newArgs = realloc(args, sizeof(char*)*(argc+1));
if(newArgs != NULL)
{
args = newArgs;
}
else
{
printf("An error while reallocating memory occurred. %s\n", strerror(errno));
exit(1);
}
args[argc] = NULL;
argc++;
call_command(args[0], args, argc);
for(int i = 0; i < argc; i++)
{
free(args[i]);
}
free(args);
}
// A function that executes passed command with args
void call_command(char* commandName, char** args, int argc)
{
// Check if it is a builtin command
if(try_shell_command(commandName, args, argc) == true)
{
return;
}
pid_t pid;
pid = fork();
if(pid < 0)
{
printf("Failed creating new process. %s\n", strerror(errno));
return;
}
else if (pid == 0)
{
if(execvp(commandName, args) == -1)
{
printf("Error executing program. %s\n", strerror(errno));
return;
}
for(int i = 0; i < argc+1; i++)
{
if(args[i])
free(args[i]);
}
if(args)
free(args);
}
else
{
// Add this process to the queue
BACKGROUND_PROCS[BACKGROUND_PROC_COUNT] = pid;
BACKGROUND_PROC_COUNT++;
}
}
// Function that checks if given command is shell builtin, and if it is, execute it, then return true
// Returns false if command is not builtin
bool try_shell_command(char* commandName, char** args, int argc)
{
if(strcmp(commandName, "cd") == 0)
{
cmd_cd(args);
return true;
}
else if(strcmp(commandName, "help") == 0)
{
cmd_help();
return true;
}
else if (strcmp(commandName, "exit") == 0)
{
printf("Bye\n");
SHELL_CLOSED = true;
return true;
}
return false;
}
// Print help message and exit
void cmd_help()
{
printf("This shell should accept usual linux shell commands. But there are built in commands too:\n");
printf("help - print this message.\n");
printf("cd [directory] - perform chdir command to change directory\n");
printf("exit - closes the shell\n");
}
// Change directory function
void cmd_cd(char** args)
{
if(args == NULL || args[1] == NULL)
{
printf("Could not change directory, given args are null");
return;
}
if(chdir(args[1]) != 0)
{
printf("Error: %s\n", strerror(errno));
return;
}
}