-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
2059 lines (1836 loc) · 69.9 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
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "shell.h"
#include "parser.h"
#include "filesystem.h"
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
job *all_jobs;
job *list_of_jobs = NULL;
background_job *all_background_jobs = NULL;
pid_t shell_pgid;
struct termios shell_tmodes;
int shell_terminal;
int shell_is_interactive;
//strings for built in functions
char *exit_string = "exit\0";
char *kill_string = "kill\0";
char *jobs_string = "jobs\0";
char *fg_string = "fg\0";
char *bg_string = "bg\0";
char *ls_string = "ls\0";
char *chmod_string = "chmod\0";
char *mkdir_string = "mkdir\0";
char *rmdir_string = "rmdir\0";
char *cd_string = "cd\0";
char *pwd_string = "pwd\0";
char *cat_string = "cat\0";
char *more_string = "more\0";
char *rm_string = "rm\0";
char *mount_string = "mount\0";
char *unmount_string = "unmount\0";
//TODO: add flags to the parser
//flags
char *F = "-F\0";
char *l = "-l\0";
//strings and variables for jobs printout
char *running = "Running\0";
char *suspended = "Suspended\0";
char *killed = "Killed\0";
char *builtInTags[NUMBER_OF_BUILT_IN_FUNCTIONS];
struct builtin allBuiltIns[NUMBER_OF_BUILT_IN_FUNCTIONS];
int root_index_into_mount_table = -1;
directory_entry *pwd_directory = NULL;
int root_directory_ft_entry = 0;
user *current_user;
user *valid_users[NUMBER_OF_VALID_USERS];
/* Main method and body of the function. */
int main (int argc, char **argv) {
EXIT = FALSE;
int mid = -1;
initializeFilesystem("DISK", &mid);
initializeShell();
buildBuiltIns(); //store all builtins in built in array
if(EXIT != TRUE) {
//ask the user to log into the shell
create_users();
login();
free(pwd_directory);
pwd_directory = f_opendir(current_user->absolute_path_home_directory);
}
while (!EXIT) {
perform_parse();
job *currentJob = all_jobs;
/* run list of jobs entered */
while (currentJob != NULL) {
if (!(currentJob->pass)) {
launchJob(currentJob, !(currentJob->run_in_background));
}
currentJob = currentJob->next_job;
}
/* add job to background if it is flagged */
job *to_suspend = all_jobs;
while (to_suspend != NULL) {
if (to_suspend->suspend_this_job) {
put_job_in_background(to_suspend, 0, SUSPENDED);
}
to_suspend = to_suspend->next_job;
}
/*Print out job status updates */
background_job *bj = all_background_jobs;
int i = 0;
while (bj != NULL) {
char *status[] = {running, suspended, killed};
i++;
if (bj->verbose) {
printf("\n[%d] %s \t\t %s\n", i, status[bj->status], bj->job_string);
bj->verbose = FALSE;
}
bj = bj->next_background_job;
}
free_all_jobs();
}
// fclose(mount_table_entry[root_index_into_mount_table])
// f_unmount(root_index_into_mount_table);
shutdownFilesystem(mid);
free_users();
/* free any background jobs still in LL before exiting */
free_background_jobs();
return EXIT_SUCCESS;
}
/* Make sure that the filesystem is set up */
void initializeFilesystem(char *disk_to_mount, int *mid) {
setup();
if(f_mount(disk_to_mount, "N/A", mid) == FALSE) {
EXIT = TRUE;
}
}
/* Make sure that the file system's memory is freed */
void shutdownFilesystem(int mid) {
f_unmount(mid);
shutdown();
}
/* Make sure the shell is running interactively as the foreground job
before proceeding. */ // modeled after https://www.gnu.org/software/libc/manual/html_node/Initializing-the-Shell.html
void initializeShell() {
/* See if we are running interactively. */
shell_terminal = STDIN_FILENO;
shell_is_interactive = isatty(shell_terminal);
if (shell_is_interactive) {
/* Loop until we are in the foreground. */
while (tcgetpgrp(shell_terminal) != (shell_pgid = getpgrp()))
kill(-shell_pgid, SIGTTIN);
/* Ignore interactive and job-control signals. */
if (signal(SIGINT, SIG_IGN) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGTERM, SIG_IGN) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGQUIT, SIG_IGN) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGTTIN, SIG_IGN) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGTTOU, SIG_IGN) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGTSTP, SIG_IGN) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
/* registering sigchild handler */
struct sigaction childreturn;
memset(&childreturn, 0, sizeof(childreturn));
childreturn.sa_sigaction = &childReturning;
sigset_t mask;
sigemptyset (&mask);
sigaddset(&mask, SIGCHLD);
childreturn.sa_mask = mask;
/* add sig set for sig child and sigtstp */
childreturn.sa_flags = SA_SIGINFO | SA_RESTART;
if (sigaction(SIGCHLD, &childreturn, NULL) < 0) {
perror("Error with sigaction for child.\n");
return;
}
/* Put ourselves in our own process group. */
shell_pgid = getpid();
if (setpgid(shell_pgid, shell_pgid) < 0) {
perror("Couldn't put the shell in its own process group.\n");
exit(1);
}
/* Grab control of the terminal. */
tcsetpgrp(shell_terminal, shell_pgid);
/* Save default terminal attributes for shell. */
tcgetattr(shell_terminal, &shell_tmodes);
} else {
perror("I am sorry, there was an error with initializing the shell.\n");
exit(EXIT_FAILURE);
}
}
/* Make array for built in commands. */
void buildBuiltIns() {
char *builtInTags[NUMBER_OF_BUILT_IN_FUNCTIONS] = {exit_string, kill_string, jobs_string, fg_string, bg_string,
ls_string,
chmod_string, mkdir_string, rmdir_string, cd_string, pwd_string,
cat_string, more_string, rm_string, mount_string,
unmount_string};
for (int i = 0; i < NUMBER_OF_BUILT_IN_FUNCTIONS; i++) {
allBuiltIns[i].tag = builtInTags[i];
if (i == 0) {
allBuiltIns[i].function = exit_builtin;
} else if (i == 1) {
allBuiltIns[i].function = kill_builtin;
} else if (i == 2) {
allBuiltIns[i].function = jobs_builtin;
} else if (i == 3) {
allBuiltIns[i].function = foreground_builtin;
} else if (i == 4) {
allBuiltIns[i].function = background_builtin;
} else if (i == 5) {
allBuiltIns[i].function = ls_builtin;
} else if (i == 6) {
allBuiltIns[i].function = chmod_builtin;
} else if (i == 7) {
allBuiltIns[i].function = mkdir_builtin;
} else if (i == 8) {
allBuiltIns[i].function = rmdir_builtin;
} else if (i == 9) {
allBuiltIns[i].function = cd_builtin;
} else if (i == 10) {
allBuiltIns[i].function = pwd_builtin;
} else if (i == 11) {
allBuiltIns[i].function = cat_builtin;
} else if (i == 12) {
allBuiltIns[i].function = more_builtin;
} else if (i == 13) {
allBuiltIns[i].function = rm_builtin;
} else if (i == 14) {
allBuiltIns[i].function = mount_builtin;
} else {
allBuiltIns[i].function = unmount_builtin;
}
}
}
void create_users() {
user *super_user = malloc(sizeof(user));
user *basic_user = malloc(sizeof(user));
memset(super_user, 0, sizeof(user));
memset(basic_user, 0, sizeof(user));
super_user->uid = 0;
basic_user->uid = 1;
//TODO: mount users at their own directories
// f_mkdir("/super");
// f_mkdir("/basic");
//
// super_user->absolute_path_home_directory = malloc(10);
// memset(super_user->absolute_path_home_directory, 0, 10);
// strcpy(super_user->absolute_path_home_directory, "/super");
//
// basic_user->absolute_path_home_directory = malloc(10);
// memset(basic_user->absolute_path_home_directory, 0, 10);
// strcpy(basic_user->absolute_path_home_directory, "/basic");
super_user->absolute_path_home_directory = "/";
basic_user->absolute_path_home_directory = "/";
super_user->name = "super";
basic_user->name = "basic";
super_user->password = "suser";
basic_user->password = "buser";
valid_users[0] = super_user;
valid_users[1] = basic_user;
}
void free_users() {
//TODO: uncomment if string comes back
// free(valid_users[0]->absolute_path_home_directory);
// free(valid_users[1]->absolute_path_home_directory);
free(valid_users[0]);
free(valid_users[1]);
}
void login() {
boolean login_valid = FALSE;
char *buffer = malloc(BUFFERSIZE);
memset(buffer, 0, BUFFERSIZE);
while (!login_valid) {
printf("Please enter a username less than 80 characters(super or basic): ");
memset(buffer, 0, BUFFERSIZE);
fgets(buffer, sizeof(buffer), stdin);
buffer[strlen(buffer)-1] = 0;
if (strcmp(valid_users[0]->name, buffer) != 0 && strcmp(valid_users[1]->name, buffer) != 0) {
printf("Invalid username. Please try again.\n");
continue;
}
//password: suser buser
printf("Please enter a password: ");
memset(buffer, 0, BUFFERSIZE);
fgets(buffer, sizeof(buffer), stdin);
buffer[strlen(buffer)-1] = 0;
if (strcmp(valid_users[0]->password, buffer) != 0 && strcmp(valid_users[1]->password, buffer) != 0) {
printf("Invalid password. Please try again.\n");
continue;
}
if (strcmp(valid_users[0]->password, buffer) == 0) {
current_user = valid_users[0];
} else {
current_user = valid_users[1];
}
free(buffer);
login_valid = TRUE;
}
}
/* Method that takes a command pointer and checks if the command is a background or foreground job.
* This method returns 0 if foreground and 1 if background */
int isBackgroundJob(job* job1) {
return job1->run_in_background == TRUE;
}
/* takes pgid to remove and removes corresponding pgid, if it exists */
void trim_background_process_list(pid_t pid_to_remove) {
background_job *cur_background_job = all_background_jobs;
background_job *prev_background_job = NULL;
while (cur_background_job != NULL) {
if (cur_background_job->pgid == pid_to_remove) { //todo: check this code, since I don't think it works correctly...
if (prev_background_job == NULL) {
background_job *temp = cur_background_job->next_background_job;
all_background_jobs = temp;
free(cur_background_job->job_string);
free(cur_background_job);
return;
}
else {
prev_background_job->next_background_job = cur_background_job->next_background_job;
free(cur_background_job->job_string);
free(cur_background_job);
return;
}
}
else{
prev_background_job = cur_background_job;
cur_background_job = cur_background_job->next_background_job;
}
}
}
job *package_job(background_job *cur_job) {
job *to_return = malloc(sizeof(job));
memset(to_return, 0, sizeof(job));
if (to_return == NULL) {
perror("I am sorry, but there was an error with malloc.\n");
return NULL;
}
to_return->pgid = cur_job->pgid;
to_return->status = cur_job->status;
to_return->full_job_string = malloc(lengthOf(cur_job->job_string) + 1);
memset(to_return->full_job_string, 0, lengthOf(cur_job->job_string) + 1);
if (to_return->full_job_string == NULL) {
perror("I am sorry, but there was an error with malloc.\n");
return NULL;
}
strcpy(to_return->full_job_string, cur_job->job_string);
return to_return;
}
void job_suspend_helper(pid_t calling_id) {
/* if job is in background, just update status */
background_job *cur_job = all_background_jobs;
while (cur_job != NULL) {
if (cur_job->pgid == calling_id) {
cur_job->status = SUSPENDED;
cur_job->verbose = TRUE;
return;
}
cur_job = cur_job->next_background_job;
}
/* other wise it must be a job being run for a first time */
job *check_foreground = all_jobs;
while (check_foreground != NULL) {
if (check_foreground->pgid == calling_id) {
check_foreground->suspend_this_job = TRUE;
return;
}
check_foreground = check_foreground->next_job;
}
}
/* child process has terminated and so we need to remove the process from the linked list (by pid) */
void childReturning(int sig, siginfo_t *siginfo, void *context) {
int signum = siginfo->si_signo;
pid_t calling_id = siginfo->si_pid;
if (signum == SIGCHLD) {
//in the case of the child being killed, remove it from the list of jobs
if(siginfo->si_code == CLD_KILLED || siginfo->si_code == CLD_DUMPED || siginfo->si_code == CLD_EXITED) {
trim_background_process_list(calling_id);
}
else if(siginfo->si_code == CLD_STOPPED) {
job_suspend_helper(calling_id);
}
}
}
/* This method is simply the remove node method called when a node needs to be removed from the list of jobs. */
void removeNode(pid_t pidToRemove) {
//look through jobs for pid of child to remove
job *currentJob = all_jobs;
process *currentProcess = NULL;
process *nextProcess = NULL;
while (currentJob != NULL) {
//the pid of the first job process matches, then update job pointer!
currentProcess = currentJob->first_process;
if (currentProcess != NULL && currentProcess->pid == pidToRemove) {
currentJob->first_process = currentProcess->next_process;
return;
} else { //look at all processes w/in job for pid not the first one
while (currentProcess != NULL) {
nextProcess = currentProcess->next_process;
if (nextProcess->pid == pidToRemove) {
//found the pidToRemove, free, and an reset pointers
currentProcess->next_process = nextProcess->next_process;
free(nextProcess);
return;
}
currentProcess = nextProcess;
}
}
//pid not found in list of current processes for prior viewed job, get next job
currentJob = currentJob->next_job;
}
}
/* Passes in the command to check. Returns the index of the built-in command if it’s in the array of
* built-in commands and -1 if it is not in the array allBuiltIns
*/
int isBuiltInCommand(process cmd) {
for (int i = 0; i < NUMBER_OF_BUILT_IN_FUNCTIONS; i++) {
if (process_equals(cmd, allBuiltIns[i])) {
//TODO: comment out when not needed
if (i == 11) {
return NOT_FOUND;
}
return i; //return index of command
}
}
return NOT_FOUND;
}
int process_equals(process process1, builtin builtin1) {
int compare_value = strcmp(process1.args[0], builtin1.tag);
if (compare_value == FALSE) {
return TRUE;
} else {
return FALSE;
}
}
/* Passes in the built-in command to be executed along with the index of the command in the allBuiltIns array. This method returns true upon success and false upon failure/error. */
int executeBuiltInCommand(process *process1, int index) {
//execute built in (testing...)
return (*(allBuiltIns[index].function))(process1->args);
}
void launchJob(job *j, int foreground) {
process *p;
pid_t pid;
int isBuiltIn;
for (p = j->first_process; p; p = p->next_process) {
isBuiltIn = isBuiltInCommand(*p);
//run as a built-in command
if (isBuiltIn != NOT_FOUND) {
executeBuiltInCommand(p, isBuiltIn);
}
else {
/* Fork the child processes. */
pid = fork();
if (pid == 0) {
/* This is the child process. */
launchProcess(p, j->pgid, j->stdin, j->stdout, j->stderr, foreground);
} else if (pid < 0) {
/* The fork failed. */
perror("fork");
exit(EXIT_FAILURE);
} else {
/* This is the parent process. */
p->pid = pid;
if (!j->pgid) {
j->pgid = pid;
}
setpgid(pid, j->pgid); //TODO: check process group ids being altered correctly
}
}
}
if (isBuiltIn == NOT_FOUND) {
if (foreground) {
put_job_in_foreground(j, 0);
} else {
sigset_t mask;
if (sigemptyset(&mask) == ERROR) {
perror("I am sorry, but sigemptyset failed.\n");
exit(EXIT_FAILURE);
}
if (sigaddset(&mask, SIGCHLD) == ERROR) {
perror("I am sorry, but sigaddset failed.\n");
exit(EXIT_FAILURE);
}
if (sigprocmask(SIG_BLOCK, &mask, NULL) == ERROR) {
perror("I am sorry, but sigprocmask failed.\n");
exit(EXIT_FAILURE);
}
put_job_in_background(j, !CONTINUE, RUNNING);
if (sigprocmask(SIG_UNBLOCK, &mask, NULL) == ERROR) {
perror("I am sorry, but sigprocmask failed.\n");
exit(EXIT_FAILURE);
}
}
}
}
/* Method to launch our process in either the foreground or the background. */
//method based off of https://www.gnu.org/software/libc/manual/html_node/Launching-Jobs.html#Launching-Jobs
void launchProcess (process *p, pid_t pgid, int infile, int outfile, int errfile, int foreground) {
pid_t pid;
/* Put the process into the process group and give the process group
the terminal, if appropriate.
This has to be done both by the shell and in the individual
child processes because of potential race conditions. */ //TODO: consider race conditions arising here!!
pid = getpid();
if (pgid == 0) {
pgid = pid;
}
if(strcmp(p->args[ZERO], "cat") == 0) {
foreground = TRUE;
}
if (setpgid(pid, pgid) < ZERO) {
perror("Couldn't put the shell in its own process group.\n");
exit(EXIT_FAILURE);
}
if (foreground) {
if (tcsetpgrp(shell_terminal, pgid) < 0) {
perror("tcsetpgrp");
exit(EXIT_FAILURE);
}
}
/* Set the handling for job control signals back to the default. */
if (signal(SIGINT, SIG_DFL) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGQUIT, SIG_DFL) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGTSTP, SIG_DFL) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGTTIN, SIG_DFL) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGTTOU, SIG_DFL) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if (signal(SIGCHLD, SIG_DFL) == SIG_ERR) {
perror("I am sorry, but signal failed.\n");
exit(EXIT_FAILURE);
}
if(strcmp(p->args[ZERO], "cat") == 0) {
cat_builtin(p->args);
}
/* Exec the new process. Make sure we exit. */
else if (execvp(p->args[ZERO], p->args) == ERROR) {
fprintf(stderr, "Error: %s: command not found\n", p->args[0]);
free_all_jobs();
}
exit(EXIT_FAILURE);
}
/* Put job j in the foreground. If cont is nonzero,
restore the saved terminal modes and send the process group a
SIGCONT signal to wake it up before we block. */
void put_job_in_foreground (job *j, int cont) {
int status;
/* Put the job into the foreground. */
if (tcsetpgrp(shell_terminal, j->pgid) == ERROR) {
perror("\"I am sorry, but tcsetpgrp failed.\n");
exit(EXIT_FAILURE);
}
if (tcgetattr(shell_terminal, &j->termios_modes) == ERROR) {
perror("I am sorry, but tcgetattr failed.\n");
exit(EXIT_FAILURE);
}
/* Wait for it to report. */
if(waitpid (j->pgid, &status, WUNTRACED) == ERROR) {
perror("I am sorry, but waitpid failed.\n");
exit(EXIT_FAILURE);
}
/* Put the shell back in the foreground. */
if (tcsetpgrp(shell_terminal, shell_pgid)== ERROR) {
perror("\"I am sorry, but tcsetpgrp failed.\n");
exit(EXIT_FAILURE);
}
/* Restore the shell’s terminal modes. */
tcsetattr(shell_terminal, TCSADRAIN, &shell_tmodes);
}
/* takes background job and gives it to background job */
void simple_background_job_setup(background_job *dest, job *org, int status)
{
dest->pgid = org->pgid;
dest->status = status;
dest->termios_modes = org->termios_modes; // <<< potential source of error here? valgrind and fg seems to be complaing about unitialized bytes
char *js = malloc(sizeof(char) * lengthOf(org->full_job_string) + 1);
memset(js, 0, sizeof(char) * lengthOf(org->full_job_string) + 1);
if(js == NULL) {
perror("I am sorry, but there was an error with malloc.\n");
exit(EXIT_FAILURE);
}
strcpy(js, org->full_job_string);
dest->job_string = js;
dest->verbose = TRUE;
dest->next_background_job = NULL;
}
/* Put a job in the background initially. If the cont argument is true, send
the process group a SIGCONT signal to wake it up. */
void put_job_in_background(job *j, int cont, int status) { //TODO: check on merge here
/* Add job to the background list with status of running */
if (!cont) {
background_job *copyOfJ = malloc(sizeof(background_job));
memset(copyOfJ, 0, sizeof(background_job));
if(copyOfJ == NULL) {
perror("I am sorry, but there was an error with malloc.\n");
exit(EXIT_FAILURE);
}
simple_background_job_setup(copyOfJ, j, status);
if (all_background_jobs == NULL) {
all_background_jobs = copyOfJ;
} else {
background_job *cur_job = all_background_jobs;
background_job *next_job = all_background_jobs->next_background_job;
while (next_job != NULL) {
background_job *temp = next_job;
next_job = cur_job->next_background_job;
cur_job = temp;
}
cur_job->next_background_job = copyOfJ;
}
}
else {
if (kill(-j->pgid, SIGCONT) < 0) {
perror("kill (SIGCONT)");
}
}
}
int arrayLength(char **array) {
int i = 0;
while (array[i] != NULL) {
i++;
}
return i;
}
/* Let's have this clean up the job list */
int exit_builtin(char **args) {
background_job *cur_background_job = all_background_jobs;
while (cur_background_job != NULL) {
if (kill(-cur_background_job->pgid, SIGKILL) < 0){
perror("kill (SIGKILL)");
}
else {
printf("KILLED pgid: %d job: %s \n", cur_background_job->pgid, cur_background_job->job_string);
}
cur_background_job = cur_background_job->next_background_job;
}
EXIT = TRUE;
return EXIT; //success
}
void background_built_in_helper(background_job *bj, int cont, int status) {
if (kill(-bj->pgid, SIGCONT) < 0) {
perror("kill (SIGCONT)");
}
background_job *current_job = all_background_jobs;
int index = 0;
while (current_job != NULL) {
index ++;
if (current_job->pgid == bj->pgid) {
current_job->status = RUNNING;
printf("[%d]\t\t%s\n", index, bj->job_string);
}
current_job = current_job->next_background_job;
}
}
background_job *get_background_from_pgid(pid_t pgid) {
background_job *current_job = all_background_jobs;
while (current_job != NULL) {
if (current_job->pgid == pgid) {
return current_job;
}
current_job = current_job->next_background_job;
}
return NULL;
}
void foreground_helper(background_job *bj) {
int status;
/* Put the job into the foreground. */
if (tcsetpgrp(shell_terminal, bj->pgid) == ERROR) {
perror("\"I am sorry, but tcsetpgrp failed.\n");
}
if (tcgetattr(shell_terminal, &bj->termios_modes) == ERROR) {
perror("I am sorry, but tcgetattr failed.\n");
}
/* Send the job a continue signal, if necessary. */
if (tcsetattr(shell_terminal, TCSADRAIN, &bj->termios_modes) == ERROR) {
perror("I am sorry, but tcsetattr failed.\n");
}
if (kill(-bj->pgid, SIGCONT) < 0)
perror("kill (SIGCONT)");
printf("%s\n", bj->job_string); //print statement
/* if the system call is interrupted, wait again */
waitpid(bj->pgid , &status, WUNTRACED);
/* Put the shell back in the foreground. */
if (tcsetpgrp(shell_terminal, shell_pgid) == ERROR) {
perror("\"I am sorry, but tcsetpgrp failed.\n");
}
/* Restore the shell’s terminal modes. */
if (tcsetattr(shell_terminal, TCSADRAIN, &shell_tmodes) == ERROR) {
perror("tcsetattr");
}
}
/* Method to take a job id and send a SIGTERM to terminate the process.*/
int kill_builtin(char **args) {
char *flag = "-9\0";
int flagLocation = 1;
int pidLocationNoFlag = 1;
int pidLocation = 2;
int minElements = 2;
int maxElements = 3;
//get args length
int argsLength = arrayLength(args);
if (argsLength < minElements || argsLength > maxElements) {
//invalid arguments
fprintf(stderr,"I am sorry, but you have passed an invalid number of arguments to kill.\n");
return FALSE;
} else if (argsLength == maxElements && args[pidLocation][ZERO] == '%') {
if (strcmp(args[flagLocation], flag) ==
ZERO) { //check that -9 flag was input correctly, otherwise try sending kill with pid
//(error checking gotten from stack overflow)
const char *nptr = args[pidLocation] + pidLocationNoFlag; /* string to read as a number */
char *endptr = NULL; /* pointer to additional chars */
int base = 10; /* numeric base (default 10) */
long long int number = 0; /* variable holding return */
/* reset errno to 0 before call */
errno = 0;
/* call to strtol assigning return to number */
number = strtoll(nptr, &endptr, base);
/* test return to number and errno values */
if (nptr == endptr) {
printf(" number : %lld invalid (no digits found, 0 returned)\n", number);
return FALSE;
} else if (errno == ERANGE && number == LONG_MIN) {
printf(" number : %lld invalid (underflow occurred)\n", number);
return FALSE;
} else if (errno == ERANGE && number == LONG_MAX) {
printf(" number : %lld invalid (overflow occurred)\n", number);
return FALSE;
} else if (errno == EINVAL) { /* not in all c99 implementations - gcc OK */
printf(" number : %lld invalid (base contains unsupported value)\n", number);
return FALSE;
} else if (errno != ZERO && number == ZERO) {
printf(" number : %lld invalid (unspecified error occurred)\n", number);
return FALSE;
} else if (errno == ZERO && nptr && *endptr != ZERO) {
printf(" number : %lld invalid (since additional characters remain)\n", number);
return FALSE;
}
//have location now in linked list
int currentNode = 0;
background_job *currentJob = all_background_jobs;
while (currentJob != NULL) {
currentNode++;
//found your node
if (currentNode == number) {
break;
} else {
currentJob = currentJob->next_background_job;
}
}
//node was not found!
if (currentNode < number || number <= ZERO) {
fprintf(stderr,"I am sorry, but that job does not exist.\n");
return FALSE;
} else {
pid_t pid = currentJob->pgid;
printf("Sent SIGKILL to %d, check jobs to see completed\n", pid);
if (kill(pid, SIGKILL) == ERROR) {
perror("I am sorry, an error occurred with kill.\n");
return FALSE; //error occurred
}
}
}
} else { //we have no flags and only kill with a pid
if (args[pidLocationNoFlag][ZERO] == '%') {
//PID is second argument
//(error checking gotten from stack overflow)
const char *nptr =
args[pidLocationNoFlag] + pidLocationNoFlag; /* string to read as a number */
char *endptr = NULL; /* pointer to additional chars */
int base = 10; /* numeric base (default 10) */
long long int number = 0; /* variable holding return */
/* reset errno to 0 before call */
errno = 0;
/* call to strtol assigning return to number */
number = strtoll(nptr, &endptr, base);
/* test return to number and errno values */
if (nptr == endptr) {
fprintf(stderr, " number : %lld invalid (no digits found, 0 returned)\n", number);
return FALSE;
} else if (errno == ERANGE && number == LONG_MIN) {
fprintf(stderr, " number : %lld invalid (underflow occurred)\n", number);
return FALSE;
} else if (errno == ERANGE && number == LONG_MAX) {
fprintf(stderr, " number : %lld invalid (overflow occurred)\n", number);
return FALSE;
} else if (errno == EINVAL) { /* not in all c99 implementations - gcc OK */
fprintf(stderr, " number : %lld invalid (base contains unsupported value)\n", number);
return FALSE;
} else if (errno != 0 && number == 0) {
fprintf(stderr, " number : %lld invalid (unspecified error occurred)\n", number);
return FALSE;
} else if (errno == 0 && nptr && *endptr != 0) {
fprintf(stderr, " number : %lld invalid (since additional characters remain)\n", number);
return FALSE;
}
//have location now in linked list
int currentNode = 0;
background_job *currentJob = all_background_jobs;
while (currentJob != NULL) {
currentNode++;
//found your node
if (currentNode == number) {
break;
} else {
currentJob = currentJob->next_background_job;
}
}
//node was not found!
if (currentNode < number || number <= 0) {
fprintf(stderr,"I am sorry, but that job does not exist.\n");
return FALSE;
} else {
pid_t pid = currentJob->pgid;
printf("Sent SIGTERM to %d, check jobs to see completed\n", pid);
if (kill(pid, SIGTERM) == -1) {
fprintf(stderr,"I am sorry, an error occurred with kill.\n");
return FALSE; //error occurred
}
}
}
return FALSE;
}
return FALSE;
}
/* Method to iterate through the linked list and print out node parameters. */
int jobs_builtin(char **args) {
background_job *currentJob = all_background_jobs;
char *status[] = {running, suspended, killed};
int jobID = 1;
if (currentJob == NULL) {} // do nothing
else {
while (currentJob != NULL) {
//print out formatted information for processes in job
printf("[%d]\t %d %s \t\t %s\n", jobID, currentJob->pgid, status[currentJob->status],
currentJob->job_string);
jobID++;
//get next job
currentJob = currentJob->next_background_job;
}
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
/* Method that sends continue signal to suspended process in background -- this is bg*/
int background_builtin(char **args) {
//get size of args
int argsLength = arrayLength(args);
int locationOfPercent = 1;
int minArgsLength = 1;
int maxArgsLength = 2;
if (argsLength < minArgsLength || argsLength > maxArgsLength) {
fprintf(stderr, "I am sorry, but that is an invalid list of commands to bg.\n");
return FALSE;
}
if (argsLength == minArgsLength) {
//bring back tail of jobs list, if it exists
background_job *currentJob = all_background_jobs;
background_job *nextJob = NULL;
if (currentJob == NULL) {
fprintf(stderr,"I am sorry, but that job does not exist.\n");
return FALSE;
}
while (currentJob != NULL) {
nextJob = currentJob->next_background_job;
if (nextJob == NULL) {
break; //want to bring back current job
}
currentJob = currentJob->next_background_job;
}