-
Notifications
You must be signed in to change notification settings - Fork 0
/
shell.c
523 lines (485 loc) · 15.6 KB
/
shell.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/* Includes */
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <stdbool.h>
/* Definitions */
#define MAX_INPUT 80
#define PATH_WORKING_DIRECTORY 80
#define FOREVER '\0'
#define DELIMS " \t\r\n"
#define READ 0
#define WRITE 1
#define SIGDET 1
/* Function for counting the number of pipes */
int count_pipes(char *s){
int i, pipes = 0;
/* If the '|' char is found, increment the pipes int */
for(i = 0; i < strlen(s); i++){
if(s[i] == '|') pipes++;
}
return pipes;
}
/* Split the input into list in list with seperated commands */
char ** makecommands(char inbuffer[], char delim[]){
char ** res = NULL;
char * p = strtok (inbuffer, delim);
int n_spaces = 0;
/* Split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, delim);
}
/* Realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
return res;
}
/* ERROR HANDLING */
/* Exit-function, bound to signal for all processes */
void exitshell(){
/* Local variables */
pid_t pid;
int status;
/* Try to create a signal, if we can't, print the perror */
if(signal(SIGQUIT, SIG_IGN) == SIG_ERR){
perror("signal registering failed");
}
/* Try to kill the process, if we can't print the error */
if (kill(-getpid(), SIGQUIT) == -1){
perror("kill failed");
}
/* Set pid to -1 until we find child */
pid = -1;
printf("Thank you, ");
sleep(1); /* Wait for everything to shutdown. */
printf("come again!\n");
/* Reap all child processes */
while(1){
pid = waitpid(-1, &status, WNOHANG);
if(pid > 1) {
if (WIFEXITED(status) || WIFSIGNALED(status)) {
printf("\nProcess %d terminated.\n", pid);
}
} else {
break;
}
}
exit(0);
}
/* Function for changing the current working directory */
void changedir(char *args){
/* Local variables */
char *cmd;
int chdirsuccess;
/* Reset errno */
errno = 0;
/* Get argument after cd */
cmd = strtok(args, "cd ");
/* If cd has no arguments */
if(cmd == NULL){
printf("%s", cmd);
/* EINVAL: invalid argument (22) */
errno = 22;
/* Throw the error for the user */
perror("Command failed");
/* Reset errno */
errno = 0;
/* cd ~, cd home */
} else if(strcmp(cmd, "~") == 0) {
/* Get the home folder from env, cd */
chdirsuccess = chdir(getenv("HOME"));
if (errno || chdirsuccess == -1) perror("Command failed");
/* Reset errno */
errno = 0;
/* cd with argument, "cd .." */
} else {
chdirsuccess = chdir(cmd);
/* Throw error if the argument was invalid */
if (errno || chdirsuccess == -1) perror("Command failed");
/* Reset errno */
errno = 0;
}
}
/*Handles all signals*/
void handler(int signum, siginfo_t* info, void* vp) {
/* If ctrl+z is pressed, print nextline */
if(signum == SIGTSTP) {
printf("\n");
return;
}
/* If ctrl+c is pressed, print nextline */
if(signum == SIGINT) {
printf("\n");
return;
}
/* If child process is exited, wait for it */
if(signum == SIGCHLD) {
pid_t wpid;
int status;
wpid = waitpid(info->si_pid, &status, WCONTINUED|WNOHANG);
/* If child process exited */
if(wpid > 0) {
/* If it exited normally */
if (WIFEXITED(status) || WIFSIGNALED(status)) {
printf("\nProcess %d terminated.\n", wpid);
/* If it was continued, wait for it */
} else if (WIFCONTINUED(status)) {
wpid = waitpid(wpid, &status, WUNTRACED);
/* If it exited normally */
if (WIFEXITED(status) || WIFSIGNALED(status)) {
printf("\nProcess %d terminated.\n", wpid);
} else if (WIFSTOPPED(status)) {
printf("\nProcess %d stopped.\n", wpid);
}
/* If stopped by signal */
} else if (WIFSTOPPED(status)) {
printf("\nProcess %d stopped.\n", wpid);
}
}
return;
}
return;
}
/* Register a signal handler */
void register_sighandler(int signal_code, void (*handler)(int, siginfo_t*, void*)) {
struct sigaction signal_parameters;
signal_parameters.sa_sigaction = handler;
sigemptyset(&signal_parameters.sa_mask);
signal_parameters.sa_flags = SA_SIGINFO;
/* Error handling*/
if(sigaction(signal_code, &signal_parameters, (void *)0) == -1) {
perror("sigaction error");
}
}
/* Errorhandler for creating processes */
void errorhandler(){
char * errormessage = "UNKNOWN";
if( EAGAIN == errno ) errormessage = "cannot allocate page table";
if( ENOMEM == errno ) errormessage = "cannot allocate kernel data";
fprintf( stderr, "fork() failed because: %s\n", errormessage );
/* Force quit the shell */
exitshell();
}
/* Create a new process */
void new_process(char inbuffer[], bool background) {
/* Local system variables */
pid_t pid;
/* Fork a new process */
pid = fork();
/* Start taking the time */
if(pid >= 0){
/* Child process */
if(pid == 0) {
char ** res;
res = makecommands(inbuffer, " ");
execvp(inbuffer, res);
perror("exec failed");
exit(1);
/* Parent process */
} else {
int returnstatus = 0;
if (pid == -1){
/* Fork failed, error messages */
errorhandler();
}
/* Foreground process */
if(!background){
waitpid(pid, &returnstatus, WUNTRACED);
}
}
}
}
/* Pipe controller function */
int piper(char *command[], char *grepargs[]){
/* Creations of fd and pipes */
int pipe_A[2];
int pipe_B[2];
int pipe_C[2];
int status;
int pipereturnA;
int pipereturnB;
int pipereturnC;
bool argument = false;
/* Processes */
pid_t pid_1, pid_2, pid_3, pid_4, wpid;
errno = 0;
/* Won't be used every time */
pid_4 = -1;
/* If grep has arguments, set the bool accordingly */
if(strcmp(command[3], "nothing") != 0){
argument = true;
}
/* Create two pipes */
pipereturnA = pipe(pipe_A);
pipereturnB = pipe(pipe_B);
/* If grep <arguments> */
if (argument){
pipereturnC = pipe(pipe_C);
if (pipereturnC == -1) perror("Fail when creating pipes");
}
/* Pipe error handling */
if (pipereturnA == -1 || pipereturnB == -1) perror("Fail when creating pipes");
/* Forking first process */
if ((pid_1 = fork()) == 0){
/* Copy the write fd from pipe_A */
dup2(pipe_A[WRITE], WRITE);
/* Close the read/write fd for pipe_A */
close(pipe_A[WRITE]);
close(pipe_A[READ]);
/* Execute first command */
execlp(command[0], command[0], NULL); /*printenv*/
perror("exec1 failed"); /* only if exec fails */
/* Error handling */
} else if (pid_1 < 0){
perror("fork1");
errorhandler();
}
if((pid_2= fork()) == 0){
dup2(pipe_A[READ],READ);
close(pipe_A[WRITE]);
close(pipe_A[READ]);
dup2(pipe_B[WRITE], WRITE);
close(pipe_B[WRITE]);
close(pipe_B[READ]);
/* If grep <argument> */
if(argument) {
/* Example: grep .c */
/* execlp(grep, [grep, -c, NULL]);*/
execvp(command[1], grepargs); /*grep c*/
} else {
execlp(command[1], command[1], NULL);
}
perror("exec2 failed"); /* only if exec fails */
/* Error handling */
} else if (pid_2 < 0){
perror("fork2");
errorhandler();
}
/* Third process */
if((pid_3 = fork()) == 0){
dup2(pipe_B[READ], READ);
close(pipe_A[WRITE]);
close(pipe_A[READ]);
if (argument){
dup2(pipe_C[WRITE], WRITE);
close(pipe_B[WRITE]);
close(pipe_B[READ]);
close(pipe_C[WRITE]);
close(pipe_C[READ]);
} else {
close(pipe_B[WRITE]);
close(pipe_B[READ]);
}
execlp(command[2], command[2], NULL); /*pager */
perror("exec3 failed"); /* only if exec fails */
/* Error handling */
} else if (pid_3 < 0){
perror("fork3");
errorhandler();
}
/* If we perform grep, there will be a fourth process */
if (argument){
if ((pid_4 = fork()) == 0){
dup2(pipe_C[READ], READ);
close(pipe_A[WRITE]);
close(pipe_A[READ]);
close(pipe_B[WRITE]);
close(pipe_B[READ]);
close(pipe_C[WRITE]);
close(pipe_C[READ]);
execlp(command[3], command[3], NULL); /*pager*/
perror("exec4 failed"); /* only if exec fails */
}
/* Error handling */
} else if (pid_4 < 0 && argument){
perror("fork4");
errorhandler();
}
close(pipe_A[WRITE]);
close(pipe_A[READ]);
close(pipe_B[WRITE]);
close(pipe_B[READ]);
if(argument){
close(pipe_C[WRITE]);
close(pipe_C[READ]);
}
/* Wait for all processes to finish */
while ((wpid = wait(&status)) > 0);
return 0;
}
/* checkenv -> printenv | sort | pager*/
/* checkenv PAGER -> printenv | grep PAGER | sort | pager*/
/* Handles the "printenv | sort | pager" or
"printenv | grep <arguments> | sort | pager" command */
void checkEnv(char args[]){
/* char *cmd; */
char *pager;
/* Ignore SIGINT in checkenv */
signal(SIGINT, SIG_IGN);
if(getenv("PAGER") == NULL) {
pager = "less";
} else {
pager = getenv("PAGER");
}
/* pager = less if it's not set */
/* Case without arg */
if(strcmp(args, "\0") == 0){
/* checkenv -> printenv | sort | pager*/
char *command[4];
char *c[1];
command[0] = "printenv";
command[1] = "sort";
command[2] = pager;
command[3] = "nothing";
c[0] = args;
if(piper(command, c) == -1) {
command[2] = "more";
piper(command, c);
}
} else {
/* checkenv .c -> printenv | grep .c | sort | pager*/
char *command[4];
char **c = makecommands(args, " ");
command[0] = "printenv";
command[1] = "grep";
command[2] = "sort";
command[3] = "less";
piper(command, c);
}
/* Enable SIGINT again */
register_sighandler(SIGINT, handler);
}
/* POLLING */
void polling(){
pid_t wpid;
int status;
/* Wait for all children */
wpid = waitpid((pid_t)-1, &status, WNOHANG|WCONTINUED);
printf("Polling processes..\n");
/* If childprocess is finished */
if(wpid > 0) {
/* If childprocess was terminated normally, or by signal*/
if (WIFEXITED(status) || WIFSIGNALED(status)) {
printf("Process %d terminated.\n", wpid);
/* If childprocess was stopped */
} else if (WIFSTOPPED(status)) {
printf("Process %d stopped.\n", wpid);
/* If it was continued */
} else if (WIFCONTINUED(status)) {
while(1) {
/* Wait for any child processes that were stopped */
wpid = waitpid(wpid, &status, WUNTRACED);
if(wpid > 0) {
if (WIFEXITED(status) || WIFSIGNALED(status)) {
printf("Process %d terminated.\n", wpid);
break;
} else if (WIFSTOPPED(status)) {
printf("Process %d stopped.\n", wpid);
break;
}
}
}
}
}
}
/* Main method */
int main(int argc,char** envp){
char inbuffer[MAX_INPUT];
/* Set the path */
char pwd[PATH_WORKING_DIRECTORY];
char *instr;
int stdinchar = 0;
errno = 0;
/* Shell info */
printf("\n\nShell for KTH OS Course, using C.\n");
printf("\nWelcome to BirdlyDee Shell! Remember: Dee's a bird!\n");
printf("Created by Oktay Bahceci and Simon Orresson\n\n");
/* Signal handlers */
register_sighandler(SIGINT, handler);
register_sighandler(SIGTSTP, handler);
if(SIGDET == 1){
register_sighandler(SIGCHLD, handler);
}
/* Parses input */
while(FOREVER != EOF){
/* Get the name of the current working directory, store it in pwd */
char *returngetcwd;
returngetcwd = getcwd(pwd, MAX_INPUT); /* char* getcwd(char* buffer, size_t size ); */
if (returngetcwd == NULL) perror("Error");
/* Print shell name and working directory */
sleep(0.4);
printf("birdly_dee:%s$ ", pwd);
/* Read data from stdin, if we can't, stop the program */
if (!fgets(inbuffer, MAX_INPUT, stdin)){
/*printf("\nFATAL ERROR: Could not read data from stdin.%d\n", errno);*/
continue;
}
/* Last character in the inbuffer is a nullpointer */
inbuffer[strlen(inbuffer)-1] = '\0';
/* Retrieve number of characters of the input */
while(inbuffer[stdinchar] == ' ' && stdinchar < strlen(inbuffer)) stdinchar++;
/* Point at the adress where the char array of the input is */
instr = &inbuffer[stdinchar];
/* carriage return */
if ((char) inbuffer[0] == 0) {
if(SIGDET == 0){
polling();
}
continue;
}
/* strcmp(x,y) == 0 if the strings match */
if(strcmp(instr, "exit") == 0) {
exitshell();
}
/* If the the first two characters are c and d -> cd */
if(instr[0] == 'c' && instr[1] == 'd'){
/* call to the changedir function */
changedir(instr);
/* If the first characters matches checkenv */
} else if(instr[0] == 'c' && instr[1] == 'h' && instr[2] == 'e' && instr[3] == 'c'
&& instr[4] == 'k' && instr[5] == 'e' && instr[6] == 'n' && instr[7] == 'v') {
/* if checkenv don't have any arguments */
if(strcmp(instr, "checkenv") == 0) {
checkEnv("\0");
/* checkenv with arguemnts */
} else {
checkEnv(instr);
}
} else {
/* create new process*/
if(count_pipes(inbuffer) == 0){
/*background process*/
if(inbuffer[strlen(inbuffer)-1] == '&') {
inbuffer[strlen(inbuffer)-1] = '\0';
new_process(inbuffer, true);
sleep(1);
/*foreground process*/
} else {
/* time measuring */
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
new_process(inbuffer, false);
gettimeofday(&tv2, NULL);
printf ("Total time = %f seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
}
}
}
if (SIGDET == 0){
polling();
}
}
return 0;
}