-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmallsh.c
492 lines (400 loc) · 13.9 KB
/
smallsh.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
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/**
* James Leflang
* CS 344: Operating Systems I
* Portfolio Project
*
* Description: This is an experimental shell that implements basic shell
* functions that are native to Linux. This is not a complete shell as some
* functions are not replicated from other shells such as bash, zcsh, etc.
*
* Licenced under BSD 2-Clause "Simplified" License
*
*/
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <stdbool.h>
#include <limits.h>
#define MAX_ARGS 512
#define MAX_LINE_LENGTH 2048
// Global flag for Backgrounding
// Unsafe but required!
bool isBack = true;
/**
* handleTSTP subroutine
* Handler for SIGTSTP to switch foreground/background modes.
*
* Args:
* int signo: Required for all handlers, unused
*
*/
void handleTSTP(int signo) {
static char *messageFore =
"Entering foreground-only mode (& is now ignored)\n";
static char *messageBack = "Exiting foreground-only mode\n";
if (isBack) {
// Write Out that we are entering Foreground-only
// And set the flag to false
write(1, messageFore, 49);
fflush(stdout);
isBack = false;
} else {
// Write Out that we are exiting Foreground-only
// And set the flag to true
write(1, messageBack, 49);
fflush(stdout);
isBack = true;
}
}
/**
* procInput subroutine
* Process the user's input for our shell into an array of args,
* and separate file names into separate pointers.
*
* Args:
* int shell_pid: Shell's PID
* bool *inBackmode: Is backgrounding needed?
* char *rFile: Input files, if in args
* char *procArr[]: Processed input
* char *oFile: Output files, if in args
*
*/
void procInput(const int shell_pid, bool *inBackmode, char *procArr[],
char *rFile, char *oFile) {
char inArgs[MAX_LINE_LENGTH], *token = NULL, *savePtr = NULL,
s_pid[128], *temp = NULL, *temp2 = NULL;
int curs, prev;
// Initialize
for (int i = 0; i < MAX_ARGS; i++)
procArr[i] = (char *)calloc(256, sizeof(char));
// Convert the shell PID to a string for later use
sprintf(s_pid, "%d", shell_pid);
// Prompt and wait for user input
printf(": ");
fflush(stdout);
fgets(inArgs, MAX_LINE_LENGTH, stdin);
// Trim newline
// https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input
// Nicer way
inArgs[strcspn(inArgs, "\n")] = '\0';
// User entered a blank
if (strcmp(inArgs, "") == 0) {
procArr[0] = '\0';
return;
}
// Tokenize the input
token = strtok_r(inArgs, " ", &savePtr);
curs = 0;
// Examine tokens for special chars and functions
while (token != NULL) {
// & -> Background process
if (strcmp(token, "&") == 0) {
// Set the background mode flag
*inBackmode = true;
}
// < -> Input Filename
else if (strcmp(token, "<") == 0) {
// Store the input file
token = strtok_r(NULL, " ", &savePtr);
strcpy(rFile, token);
}
// > -> Output Filename
else if (strcmp(token, ">") == 0) {
// Store the output file
token = strtok_r(NULL, " ", &savePtr);
strcpy(oFile, token);
}
// User External Commands
else {
// Allocate the buffers
temp = (char *)calloc(128, sizeof(char));
temp2 = (char *)calloc(128, sizeof(char));
// Set a var for checking if we have more than one expansion
prev = 0;
// Go through the arg for $$
for (int j = 0; j < strlen(token); j++) {
// If $$ is the current chars, expand to shell_pid
if ((token[j] == '$') && (token[j + 1] == '$')) {
// Replace PID in-place
// Grab the first half
if (prev == 0) {
// First time of duping
temp = strndup(token, j);
} else {
// Get the segment of token between the previous and
// the current index
temp = strndup(token + prev, j);
}
// Grab the second half
temp2 = strdup(token + j + 2);
// Add the PID
strcat(temp, s_pid);
// Add the second half
strcat(temp, temp2);
// Save where the previous $$ was
prev = j + 2;
}
}
// Save to the array
if (strcmp(temp, "") != 0) {
procArr[curs] = temp;
} else {
temp = strdup(token);
procArr[curs] = temp;
}
// Free
if (temp2 != NULL) free(temp2);
temp2 = NULL;
}
// Increment the counter
curs++;
token = strtok_r(NULL, " ", &savePtr);
}
// Add an additional NULL
procArr[curs] = NULL;
}
/**
* printStatus subroutine
* Prints the current status of the process
*
* Args:
* int childStatus: Status value of the child process
*
*/
void printStatus(int childStatus) {
if (WIFEXITED(childStatus)) {
// We have an exit status
printf("exit value %d\n", WEXITSTATUS(childStatus));
fflush(stdout);
} else {
// we got a signal from the user
printf("terminated by signal %d\n", WTERMSIG(childStatus));
fflush(stdout);
}
}
/**
* execUserCMD subroutine
* Executes a user command as a child process
*
* Args:
* char *input[]: Array of user command args
* bool *isBackground: Are we running in background
* int status: Process status
* struct sigaction sa_ign: Process signal handler
* struct sigaction sa_sigint: Process signal handler
* char *inFile: Input file
* char *outFile: Output file
*
*/
void execUserCMD(char *input[], bool *isBackground, int status,
struct sigaction sa_tstp, struct sigaction sa_sigint,
char *inFile, char *outFile) {
int openFD, writeFD, resultStat;
pid_t childPid = -5, actPid = -5;
// This mirrors Exploration: Process API - Executing a New Program
// Spawn the child
childPid = fork();
switch (childPid) {
case -1:
// Could not spawn a child
perror("Spawn Failed!\n");
fflush(stdout);
exit(1);
break;
case 0:
// Take the handler, now hook ^Z
sigaction(SIGTSTP, &sa_tstp, NULL);
// And if we are not in the background, now hook ^C
if (!*isBackground) sigaction(SIGINT, &sa_sigint, NULL);
// If the user specified an input file redirect
if (strcmp(inFile, "") != 0) {
// Open the input file
openFD = open(inFile, O_RDONLY);
// Check the input file descriptor
if (openFD == -1) {
perror("Unable to open input file");
fflush(stdout);
exit(1);
}
// Copy the descriptor and assign
resultStat = dup2(openFD, 0);
// If the dup2 did not function correctly
if (resultStat == -1) {
perror("Unable to assign input file");
fflush(stdout);
exit(2);
}
// Close
fcntl(openFD, F_SETFD, FD_CLOEXEC);
// If the input file is empty and we are in the background
} else if ((strcmp(inFile, "") == 0) && *isBackground) {
// Redirect to /dev/null
openFD = open("/dev/null", O_RDONLY);
// Check the input file descriptor
if (openFD == -1) {
perror("Unable to open /dev/null");
fflush(stdout);
exit(1);
}
// Copy the descriptor and assign
resultStat = dup2(openFD, 0);
// If the dup2 did not function correctly
if (resultStat == -1) {
perror("Unable to assign /dev/null");
fflush(stdout);
exit(2);
}
// Close
fcntl(openFD, F_SETFD, FD_CLOEXEC);
}
// If the user specified an output file redirect
if (strcmp(outFile, "") != 0) {
// Open the output file
// The 0640 permissions is only allowed (no others)
writeFD = open(outFile, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP);
// Check the output file descriptor
if (writeFD == -1) {
perror("Unable to open output file");
fflush(stdout);
exit(1);
}
// Copy the descriptor and assign
resultStat = dup2(writeFD, 1);
// If the dup2 did not function correctly
if (resultStat == -1) {
perror("Unable to assign output file");
fflush(stdout);
exit(2);
}
// Close
fcntl(writeFD, F_SETFD, FD_CLOEXEC);
// If there is no output redirect and we are in the background
} else if ((strcmp(outFile, "") == 0) && *isBackground) {
// Redirect to /dev/null
writeFD = open("/dev/null", O_WRONLY);
// Check the output file descriptor
if (writeFD == -1) {
perror("Unable to open /dev/null");
fflush(stdout);
exit(1);
}
// Copy the descriptor and assign
resultStat = dup2(writeFD, 1);
// If the dup2 did not function correctly
if (resultStat == -1) {
perror("Unable to assign /dev/null");
fflush(stdout);
exit(2);
}
// Close
fcntl(openFD, F_SETFD, FD_CLOEXEC);
}
// Execute the user's command
if (execvp(input[0], input) == -1) {
// There was no valid command
printf("%s: no such file or directory\n", input[0]);
fflush(stdout);
exit(2);
}
break;
default:
// Check for a background task and wait
if (*isBackground && isBack) {
actPid = waitpid(childPid, &status, WNOHANG);
printf("background pid is %d\n", childPid);
fflush(stdout);
} else {
// Run the forground process
actPid = waitpid(childPid, &status, 0);
}
break;
}
// When a child has finished
while ((childPid = waitpid(-1, &status, WNOHANG)) > 0) {
// Tell the user it is done
printf("background pid %d is done: ", childPid);
fflush(stdout);
printStatus(status);
}
}
int main(void) {
int pid = getpid(), exitVal = 0;
bool isExit = false, isBackgrounded = false, runLoop = true;
char *inFile = NULL, *outFile = NULL, *input[MAX_ARGS], path[PATH_MAX];
// Signal structs
struct sigaction small_sigint = {0}, small_sigtstp = {0};
// Allocate the filename buffers
inFile = (char *)calloc(256, sizeof(char));
outFile = (char *)calloc(256, sizeof(char));
// Make the Signal Handlers
small_sigint.sa_handler = SIG_DFL;
sigfillset(&small_sigint.sa_mask);
small_sigint.sa_flags = SA_RESTART;
sigaction(SIGINT, &small_sigint, NULL);
small_sigtstp.sa_handler = handleTSTP;
sigfillset(&small_sigtstp.sa_mask);
small_sigtstp.sa_flags = SA_RESTART;
sigaction(SIGTSTP, &small_sigtstp, NULL);
// Main Run Loop
while (runLoop) {
// Get and process stdin
procInput(pid, &isBackgrounded, input, inFile, outFile);
// Ignore comments and blanks
if ((strncmp(input[0], "#", 1) == 0) ||
(strcmp(input[0], "\0") == 0)) {
continue;
}
// Exit commanded
else if (strcmp("exit", input[0]) == 0) {
runLoop = false;
}
// Change Directory "cd" commanded
else if (strcmp("cd", input[0]) == 0) {
// User specified a directory to change to
if (input[1] != NULL) {
// If the directory does not exist, then perror
if (chdir(input[1]) == -1) {
printf("No directory found named %s", input[1]);
fflush(stdout);
}
} else {
// Go to HOME
getcwd(path, sizeof(path));
chdir(path);
}
}
// Status commanded
else if (strcmp("status", input[0]) == 0) {
printStatus(exitVal);
}
// Execute user command
else {
execUserCMD(input, &isBackgrounded, exitVal, small_sigtstp,
small_sigint, inFile, outFile);
}
// Reset the runtime vars
isBackgrounded = false;
inFile[0] = '\0';
outFile[0] = '\0';
for (int i = 0; i < MAX_ARGS; i++) {
input[i] = '\0';
}
}
// Clean Up
if (inFile != NULL) free(inFile);
inFile = NULL;
if (outFile != NULL) free(outFile);
outFile = NULL;
for (int i = 0; i < MAX_ARGS; i++) {
if (input[i] != NULL) free(input[i]);
input[i] = NULL;
}
return EXIT_SUCCESS;
}