-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshell.c
More file actions
711 lines (656 loc) · 17 KB
/
shell.c
File metadata and controls
711 lines (656 loc) · 17 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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <error.h>
#include <sys/wait.h>
#include <ctype.h>
#include "job_node.h"
#include "dlist.h"
#include "shell.h"
#include "tokenizer.h"
#define FALSE 0
#define TRUE 1
#define BUFSIZE 20
#define NOTKNOWN -1
#define SUCCESS 0
#define FAILURE -1
#define TOBG "bg"
#define TOFG "fg"
#define KILL "kill"
#define JOBS "jobs"
#define EXIT "exit"
// enums
enum status{background, foreground, suspended};
enum flags{ fg_to_sus,
sus_to_bg,
bg_to_fg,
terminated,
start_bg};
enum special_inputs{delim_bg = '&', delim_mult = ';'};
// job lists
dlist sus_bg_jobs;
// globals
// terminal attribute related globals
pid_t shell_pid;
pid_t shell_gpid;
struct termios mysh;
int mysh_fd = STDIN_FILENO;
struct sigaction sa;
/* ======================= Initializing Job List ============================ */
void init_joblists() {
sus_bg_jobs = dlist_new();
}
/* ========================== Handle Signals ============================== */
/*
Signal handler for SIGCHLD
*/
void sigchld_handler(int signal, siginfo_t* sg, void* oldact) {
pid_t childpid = sg->si_pid;
int status = sg->si_code;
if(status == CLD_EXITED) {
update_list(childpid, terminated);
return;
} else if (status == CLD_KILLED) {
update_list(childpid, terminated);
return;
} else if (status == CLD_STOPPED) {
update_list(childpid, fg_to_sus);
return;
} else if (status == CLD_CONTINUED) {
update_list(childpid, sus_to_bg);
return;
} else if (status == CLD_TRAPPED) {
return;
} else if(status == CLD_DUMPED) {
return;
}
return;
}
/*
set up signal mask and register signal handler
*/
int set_up_signals() {
sigset_t shellmask;
sigemptyset(&shellmask);
sigaddset(&shellmask, SIGINT);
sigaddset(&shellmask, SIGTERM);
sigaddset(&shellmask, SIGTTOU);
sigaddset(&shellmask, SIGTTIN);
sigaddset(&shellmask, SIGQUIT);
sigaddset(&shellmask, SIGTSTP);
sigprocmask(SIG_BLOCK, &shellmask, NULL);
sa.sa_flags = SA_SIGINFO | SA_RESTART;
sa.sa_sigaction = sigchld_handler;
sigaction(SIGCHLD, &sa, NULL);
return TRUE;
}
/* ============================= update list ============================ */
/*
update background and stopped job list
*/
int update_list(pid_t pid, int flag) {
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset, SIGCHLD);
sigprocmask(SIG_BLOCK, &sset, NULL);
if(flag == terminated) {
int result = dlist_remove_bypid(sus_bg_jobs, pid);
sigprocmask(SIG_UNBLOCK, &sset, NULL);
if(result == FALSE) {
return FALSE;
}
return TRUE;
}
if(flag == bg_to_fg) {
int result = dlist_remove_bypid(sus_bg_jobs, pid);
sigprocmask(SIG_UNBLOCK, &sset, NULL);
if(result == FALSE) {
return FALSE;
}
return TRUE;
}
if(flag == fg_to_sus) {
job_node* find = dlist_get_bypid(sus_bg_jobs, pid);
if(find == NULL) {
sigprocmask(SIG_UNBLOCK, &sset, NULL);
return FALSE;
} else {
find->status = suspended;
}
sigprocmask(SIG_UNBLOCK, &sset, NULL);
return TRUE;
}
if(flag == sus_to_bg) {
job_node* find = dlist_get_bypid(sus_bg_jobs, pid);
if(find == NULL) {
sigprocmask(SIG_UNBLOCK, &sset, NULL);
return FALSE;
}
find->status = background;
sigprocmask(SIG_UNBLOCK, &sset, NULL);
return TRUE;
}
return TRUE;
}
/* =============================== read in ==================================== */
/*
read in the input and add one jobnode(with original input)
*/
char* read_input() {
size_t readn;
char* input = NULL;
if(getline(&input, &readn, stdin) < 0) {
printf("getline from stdin failed! \n");
free(input);
input = NULL;
return input;
}
return input;
}
/* ========================= for "jobs" command ========================= */
/*
execute "jobs" command
*/
void print_jobs(dlist jobs) {
int length = 15;
job_node* top = get_head(jobs);
if(jobs == NULL) {
printf("No jobs available.\n");
} else if (top == NULL) {
printf("No jobs available.\n");
}
while(top != NULL) {
char* status = malloc(sizeof(char) * length);
switch(top->status) {
case background:
strcpy(status, "background");
break;
case foreground:
strcpy(status, "foreground");
break;
case suspended:
strcpy(status, "stopped");
break;
}
printf("%d. pid: %d pgid: %d %s %s\n", top->index, top->pid, top->gpid, get_input(top), status);
top = top->next;
free(status);
}
}
/* ============================== bring to fg, bg, and kill =============================== */
/*
bringing a process to background
*/
int bring_tobg(parse_output* p) {
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset, SIGCHLD);
int result = TRUE;
int no_arg = 1;
int job_index;
job_node* job;
if(p->num == no_arg) { // when bg has no argument
job = get_tail(sus_bg_jobs);
if(job != NULL) {
if(job->status == suspended) {
int killresult = kill(job->gpid, SIGCONT);
if(killresult == 0) {
sigprocmask(SIG_BLOCK, &sset, NULL);
job->status = background;
sigprocmask(SIG_UNBLOCK, &sset, NULL);
result = TRUE;
} else {
perror("Sending SIGCONT to process group failed: ");
}
} else if(job->status == background) {
printf("Process group %d already in background\n", job->gpid);
}
} else {
printf("No job in joblist\n");
}
} else {
for(int i = 1; i < p->num; i++) {
job_index = to_int(p->tasks[i]);
if(job_index != 0) {
job = dlist_get(sus_bg_jobs,job_index);
if(job != NULL) {
if(job->status == suspended) {
int killresult = kill(job->gpid, SIGCONT);
if(killresult != 0) {
perror("Sending SIGCONT in bring to background: ");
}
} else if(job->status == background) {
printf("Process %d already in background\n", job->gpid);
}
} else {
printf("Process %d not in job list\n", job_index);
}
} else {
printf("Invalid index %d\n", job_index);
}
}
}
return result;
}
/*
- execute 'fg %<#>' commands
- bring a process to foreground
- if the process bringing to foreground is stopped, a SIGCONT is sent
*/
int bring_tofg(parse_output* p) {
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset, SIGCHLD);
int result = TRUE;
int no_arg = 1;
int toint;
job_node* job;
if(p->num == no_arg) { // when bg has no argument
job = get_tail(sus_bg_jobs);
} else {
for(int i = 1; i < p->num; i++) {
toint = to_int(p->tasks[i]);
if(toint != FALSE) {
job = dlist_get(sus_bg_jobs, toint);
if(job == NULL) {
continue;
} else {
break;
}
}
}
}
if(job == NULL) {
printf("Process group %d not in job list\n", toint);
return TRUE;
}
if (job->status == suspended) {
if(kill(job->gpid, SIGCONT) != 0) {
perror("Failed to send signal: ");
return TRUE;
}
}
if(tcsetpgrp(mysh_fd, job->gpid) == FAILURE) {
perror("bringfg: set process to fg failed: ");
return TRUE;
}
if(tcsetattr(mysh_fd, TCSADRAIN, &job->jmode) != FAILURE) {
int stat;
int oldpid = job->pid;
int oldgid = job->gpid;
char* oldinput = (char*)malloc(sizeof(char) * (strlen(job->original_input) + 1));
strcpy(oldinput, job->original_input);
sigprocmask(SIG_BLOCK, &sset, NULL);
dlist_remove_bypid(sus_bg_jobs, oldpid);
sigprocmask(SIG_UNBLOCK, &sset, NULL);
waitpid(oldpid, &stat, WUNTRACED);
if(WIFSTOPPED(stat)) {
struct termios childt;
tcgetattr(STDOUT_FILENO, &childt);
sigprocmask(SIG_BLOCK, &sset, NULL);
job_node* newjob = new_node(dlist_size(sus_bg_jobs) + 1, suspended, oldpid, oldgid, oldinput, NULL, NULL);
dlist_push_end(sus_bg_jobs, newjob);
sigprocmask(SIG_UNBLOCK, &sset, NULL);
free(oldinput);
} else {
free(oldinput);
}
tcsetpgrp(mysh_fd, shell_gpid);
tcsetattr(mysh_fd, TCSADRAIN, &mysh);
} else {
perror("Setting process to foreground: ");
}
return result;
}
/*
- command 'kill' for killing Process
- does not allow user input job index without '%'
- "-9" flag for sending SIGKILL
*/
int kill_process(parse_output* p) {
int no_arg = 1;
int is_sigkill = 3;
int is_sigterm = 2;
int flag_index = 1;
sigset_t sset;
sigemptyset(&sset);
job_node* job;
sigaddset(&sset, SIGCHLD);
if(p->num == no_arg) {
printf("kill: usage: kill -flag(optional) job_index(integer)\n");
return TRUE;
} else {
int sigkill = (strcmp(p->tasks[flag_index], "-9") == 0);
if(sigkill) {
if(p->num != is_sigkill) {
printf("kill: usage: kill -flag(optional) job_index(integer)\n");
return TRUE;
}
} else {
if(p->num != is_sigterm) {
printf("kill: usage: kill -flag(optional) job_index(integer)\n");
return TRUE;
}
}
int indexnum = sigkill ? 2 : 1;
if((char)p->tasks[indexnum][0] != '%') {
printf("kill: Operating not permitted\n");
return TRUE;
} else {
int job_index = to_int(p->tasks[indexnum]);
if(job_index == FALSE) {
printf("kill: usage: kill -flag(optional) job_index(integer)\n");
return TRUE;
} else {
job = dlist_get(sus_bg_jobs, job_index);
if(job == NULL) {
printf("kill: no such job");
return TRUE;
} else {
if(job->status == suspended) {
if(kill(job->gpid, SIGCONT) == FAILURE) {
perror("Continue job failed: ");
}
}
if(kill(job->gpid, sigkill ? SIGKILL : SIGTERM) == FAILURE) {
perror("kill: sending signal: ");
}
return TRUE;
}
}
}
}
return TRUE;
}
/* ============================== executions =============================== */
/*
launch a process in background
*/
int execute_bg(char* task) {
int result = TRUE;
struct termios term;
sigset_t sset;
job_node* newjob = new_node(dlist_size(sus_bg_jobs) + 1, background, NOTKNOWN, NOTKNOWN, task, NULL, NULL);
sigemptyset(&sset);
sigaddset(&sset, SIGCHLD);
sigprocmask(SIG_BLOCK, &sset, NULL);
dlist_push_end(sus_bg_jobs, newjob);
sigprocmask(SIG_UNBLOCK, &sset, NULL);
parse_output* p = parse_input(task, " ");
if(p->num == 0) {
printf("Invalid Input\n");
free_parse_output(p);
return TRUE;
}
if(strcmp(p->tasks[0], JOBS) == 0) {
print_jobs(sus_bg_jobs);
result = TRUE;
} else if(strcmp(p->tasks[0], TOBG) == 0) {
result = bring_tobg(p);
} else if(strcmp(p->tasks[0], TOFG) == 0) {
result = bring_tofg(p);
} else if (strcmp(p->tasks[0], KILL) == 0) {
kill_process(p);
} else if(strcmp(p->tasks[0], EXIT) == 0) {
free_parse_output(p);
result = FALSE;
return result;
}else {
pid_t pid = fork();
if(pid < 0) {
perror("Fork failed: ");
free_parse_output(p);
result = TRUE;
return result;
} else if (pid == 0) {
// in child
pid_t chpid = getpid();
if(setpgid(chpid, chpid) < 0 ) {
perror("Set child gid failed: ");
free_parse_output(p);
result = TRUE;
exit(SUCCESS);
}
signal (SIGINT, SIG_DFL);
signal (SIGQUIT, SIG_DFL);
signal (SIGTSTP, SIG_DFL);
signal (SIGTTIN, SIG_DFL);
signal (SIGTTOU, SIG_DFL);
signal (SIGTERM, SIG_DFL);
if(execvp(p->tasks[0], p->tasks) < 0) {
perror("Execution error ");
result = TRUE;
free_parse_output(p);
exit(SUCCESS);
}
free_parse_output(p);
exit(SUCCESS);
} else if(pid > 0){
int stat;
setpgid(pid, pid);
setpgid(getpid(), getpid());
tcgetattr(mysh_fd, &term);
sigprocmask(SIG_BLOCK, &sset, NULL);
newjob->pid = pid;
newjob->gpid = getpgid(pid);
newjob->jmode = term;
sigprocmask(SIG_UNBLOCK, &sset, NULL);
waitpid(pid, &stat, WNOHANG);
tcsetpgrp(mysh_fd, getpgid(getpid()));
tcsetattr(mysh_fd, TCSADRAIN, &mysh);
}
}
free_parse_output(p);
return result;
}
/*
launch a process in foreground
*/
int execute_fg(char* task) {
int result = TRUE;
struct termios jterm;
parse_output* p;
p = parse_input(task, " ");
int stat;
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset, SIGCHLD);
if(p->num == 0) {
free_parse_output(p);
result = TRUE;
return result;
}
if(strcmp((char*)p->tasks[0], JOBS) == 0) {
print_jobs(sus_bg_jobs);
result = TRUE;
} else if(strcmp(p->tasks[0], TOBG) == 0) {
result = bring_tobg(p);
result = TRUE;
} else if(strcmp(p->tasks[0], TOFG) == 0) {
result = bring_tofg(p);
} else if (strcmp(p->tasks[0], KILL) == 0) {
kill_process(p);
} else if(strcmp((char*)p->tasks[0], EXIT) == 0) {
free_parse_output(p);
result = FALSE;
return result;
}else {
pid_t pid = fork();
if(pid < 0) {
perror("Fork failed: ");
free_parse_output(p);
result = TRUE;
return result;
} else if (pid == 0) {
pid_t chpid = getpid();
if(setpgid(chpid, chpid) < 0 ) {
perror("Set child gid failed: ");
free_parse_output(p);
result = TRUE;
exit(SUCCESS);
}
signal (SIGINT, SIG_DFL);
signal (SIGQUIT, SIG_DFL);
signal (SIGTSTP, SIG_DFL);
signal (SIGTTIN, SIG_DFL);
signal (SIGTTOU, SIG_DFL);
signal (SIGTERM, SIG_DFL);
if(execvp(p->tasks[0], p->tasks) < 0) {
perror("Execution error ");
result = TRUE;
free_parse_output(p);
exit(SUCCESS);
}
free_parse_output(p);
exit(SUCCESS);
} else if (pid > 0) {
if(setpgid(getpid(), getpid()) < 0) {
perror("Parent: Set parent gid in parent failed: ");
free_parse_output(p);
return TRUE;
} else if(setpgid(pid, pid) < 0) {
perror("Parent: set child gid in parent failed: ");
free_parse_output(p);
return TRUE;
}
if(tcsetpgrp(mysh_fd, getpgid(pid)) != SUCCESS) {
perror("Setting child process to foreground failed\n");
free_parse_output(p);
return TRUE;
}
tcgetattr(mysh_fd, &jterm);
waitpid(pid, &stat, WUNTRACED);
if(WIFSTOPPED(stat)){
sigprocmask(SIG_BLOCK, &sset, NULL);
job_node* newjob = new_node(dlist_size(sus_bg_jobs) + 1, suspended, pid, getpgid(pid), task, NULL, NULL);
newjob->jmode = jterm;
dlist_push_end(sus_bg_jobs, newjob);
sigprocmask(SIG_UNBLOCK, &sset, NULL);
}
if(tcsetpgrp(mysh_fd, shell_gpid) == FAILURE) {
perror("Setting shell back to foreground: ");
free_parse_output(p);
return TRUE;
}
if(tcsetattr(mysh_fd, TCSADRAIN, &mysh) == FAILURE) {
perror("Giving terminal control back to shell: ");
free_parse_output(p);
return TRUE;
}
}
// free_parse_output(p);
}
free_parse_output(p);
return result;
}
/* ============================ Free Memory ============================= */
void free_joblists() {
dlist_free(sus_bg_jobs);
}
/* =========================== useful function =========================== */
/*
- convert a string of ints to integer
- allows non-digit chars inside the string, will extract the number and calculate the integer
- for instance: "#1#2#2" converts to 122
*/
int to_int(char* str) {
int len = strlen(str);
int result = FALSE;
for(int i = 0; i < len; i ++) {
if(isdigit(str[i]) != 0) {
result *= 10;
result += str[i] - '0';
}
}
return result;
}
/* ================================ MAIN ============================= */
int main(int argc, char* argv[]){
// sets up
set_up_signals();
int run = TRUE;
shell_pid = getpid();
if(setpgid(shell_pid, shell_pid) < 0) {
perror("Reset shell gpid failed\n");
exit(FALSE);
}
shell_gpid = getpgid(shell_pid);
if(shell_gpid != tcgetpgrp(mysh_fd)) {
int result = tcsetpgrp(mysh_fd, shell_gpid);
if(result < 0) {
perror("Setting shell to foreground failed\n");
}
}
init_joblists();
tcgetattr(mysh_fd, &mysh);
do {
printf("mysh > ");
char* input = read_input();
if (input==NULL){
run = TRUE;
free(input);
continue;
}
parse_output* newline = parse_input(input, "\n");
if(newline->num == 1) {
run = TRUE;
free(input);
free_parse_output(newline);
continue;
}
parse_output* jobs = parse_input(newline->tasks[0], ";");
int symbolnum = 0;
for(int i = 0; i < jobs->num; i++) {
if(strcmp(jobs->tasks[i], ";") == 0) {
free(jobs->tasks[i]);
jobs->tasks[i] = NULL;
symbolnum ++;
}
}
int jobnum = jobs->num - symbolnum;
if(jobnum == 0) {
run = TRUE;
free_parse_output(jobs);
free_parse_output(newline);
free(input);
continue;
}
int job = 0;
for(int i = 0; i < jobs->num; i++) {
if(jobs->tasks[i] != NULL){
job = i;
break;
}
}
for(int i = job; i < jobnum; i ++) {
parse_output* smalljob = parse_input(jobs->tasks[job], "&");
for(int j = 0; j < smalljob->num; j++) {
if(strcmp(smalljob->tasks[j], "&") != 0) {
if(j == smalljob->num - 1) {
run = execute_fg(smalljob->tasks[j]);
} else if(strcmp(smalljob->tasks[j+1], "&") == 0) {
run = execute_bg(smalljob->tasks[j]);
}
} else {
continue;
}
}
job += 2;
free_parse_output(smalljob);
}
free_parse_output(jobs);
free_parse_output(newline);
free(input);
} while (run);
free_joblists();
}