-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuqparallel.c
More file actions
968 lines (840 loc) · 27.8 KB
/
uqparallel.c
File metadata and controls
968 lines (840 loc) · 27.8 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
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
#include <csse2310a3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <signal.h>
#include <getopt.h>
#include <sys/wait.h>
//REF:chatGPT help me define the value name
#define DEFAULT_MAX_JOBS 110
#define EXIT_USAGE_ERROR 5
#define EXIT_SIGNAL_TERMINATION 70
#define EXIT_EMPTY_COMMAND 80
#define EXIT_INTERRUPTED 8
volatile bool interrupted = false;
typedef struct {
int maxJobs;
bool abortOnError;
bool printOnly;
bool usePipe;
char* argsFile;
char** cmd;
int cmdCount;
char** perTaskArgs;
int perTaskArgsCount;
} Options;
typedef struct {
char** args;
int argCount;
pid_t pid;
int status;
bool completed;
} Task;
//functions
//REF:chatGPT help me rename the function name to be more clear
void parse_arguments(int argc, char** argv, Options* options);
void print_usage(void);
void execute_tasks(Options* options);
void read_args_from_file(Options* options, Task*** tasks, int* taskCount);
void read_args_from_stdin(Options* options, Task*** tasks, int* taskCount);
void create_tasks_from_cmdline(Options* options, Task*** tasks, int* taskCount);
void execute_task(Task* task, int stdinFd, int stdoutFd);
void print_task(int jobNum, Task* task, bool isPipe);
void handle_sigint(int sig);
void setup_signal_handlers(void);
void free_task(Task* task);
void free_tasks(Task** tasks, int taskCount);
void free_options(Options* options);
bool reap_tasks(Task** tasks, int taskCount, bool waitForAll);
void terminate_tasks(Task** tasks, int taskCount, int signal);
int count_running_tasks(Task** tasks, int taskCount);
void wait_for_one_second(void);
void execute_pipeline(Options* options, Task** tasks, int taskCount);
//main function
int main(int argc, char* argv[]){
//argc--; // argc-- to skip the program name
//argv++; // argv++ to point to the first argument
//printf("Hello\n");
//printf("have a good day\n");
Options options = {
.maxJobs = DEFAULT_MAX_JOBS,
.abortOnError = false,
.printOnly = false,
.usePipe = false,
.argsFile = NULL,
.cmd = NULL,
.cmdCount = 0,
.perTaskArgs = NULL,
.perTaskArgsCount = 0
};
parse_arguments(argc, argv, &options);//parse command line
setup_signal_handlers(); //set up signal handler
execute_tasks(&options);
free_options(&options);
return 0;
}
void setup_signal_handlers(void) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handle_sigint;
sigaction(SIGINT, &sa, NULL);
}
void handle_sigint(int sig) {
(void)sig; // Unused parameter
interrupted = true;
}
void print_usage(void) {
fprintf(stderr, "Usage: ./uqparallel [--jobs n] [--abort-on-error] "
"[--print] [--pipe] [--args-file argument-file] "
"[cmd [fixed-args ...]] [::: per-task-args ...]\n");
}
void parse_arguments(int argc, char** argv, Options* options) {
static struct option longOptions[] = { //define the long options
{"jobs", required_argument, 0, 'j'},
{"abort-on-error", no_argument, 0, 'a'},
{"print", no_argument, 0, 'p'},
{"pipe", no_argument, 0, 'i'},
{"args-file", required_argument, 0, 'f'},
{0, 0, 0, 0}
};
opterr = 0;
int opt;
int optionIndex = 0;
bool foundTripleColon = false;
//add duplicate check signal
bool seenJobs = false;
bool seenAbort = false;
bool seenPrint = false;
bool seenPipe = false;
bool seenArgsFile = false;
while ((opt = getopt_long(argc, argv, "", longOptions, &optionIndex)) != -1) {
//REF: chatGPT help me recode switch part
switch (opt) {
case 'j': {
if (seenJobs) {
print_usage();
exit(EXIT_USAGE_ERROR);
}
seenJobs = true;
char* endptr;
options->maxJobs = strtol(optarg, &endptr, 10);
if (*endptr != '\0' || options->maxJobs < 1 ||
options->maxJobs > 110) {
print_usage();
exit(EXIT_USAGE_ERROR);
}
break;
}
case 'a':
if (seenAbort) {
print_usage();
exit(EXIT_USAGE_ERROR);
}
seenAbort = true;
options->abortOnError = true;
break;
case 'p':
if (seenPrint) {
print_usage();
exit(EXIT_USAGE_ERROR);
}
seenPrint = true;
options->printOnly = true;
break;
case 'i':
if (seenPipe) {
print_usage();
exit(EXIT_USAGE_ERROR);
}
seenPipe = true;
options->usePipe = true;
break;
case 'f':
if (seenArgsFile) {
print_usage();
exit(EXIT_USAGE_ERROR);
}
seenArgsFile = true;
if (optarg[0] == '\0') {
print_usage();
exit(EXIT_USAGE_ERROR);
}
options->argsFile = strdup(optarg);
break;
case '?':
print_usage();
exit(EXIT_USAGE_ERROR);
default:
print_usage();
exit(EXIT_USAGE_ERROR);
}
}
//check the remainiung arguments for cmd and :::
if (optind < argc) {
int i;
for (i = optind; i < argc; i++) {
if (strcmp(argv[i], ":::") == 0) {
foundTripleColon = true;
// Save command and fixed args
if (i > optind) {
options->cmdCount = i - optind;
options->cmd = (char**)malloc(options->cmdCount * sizeof(char*));
if (!options->cmd) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
for (int j = 0; j < options->cmdCount; j++) {
options->cmd[j] = strdup(argv[optind + j]);
}
}
// Save per-task args
options->perTaskArgsCount = argc - i - 1;
if (options->perTaskArgsCount > 0) {
options->perTaskArgs =
(char**)malloc(options->perTaskArgsCount * sizeof(char*));
if (!options->perTaskArgs) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
for (int j = 0; j < options->perTaskArgsCount; j++) {
options->perTaskArgs[j] = strdup(argv[i + 1 + j]);
}
}
break;
}
}
if (!foundTripleColon) {
options->cmdCount = argc - optind;
options->cmd =(char**) malloc(options->cmdCount * sizeof(char*));
if (!options->cmd) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
for (int j = 0; j < options->cmdCount; j++) {
options->cmd[j] = strdup(argv[optind + j]);
}
}
}
if (options->argsFile != NULL && foundTripleColon) {
// Can't have both --args-file and :::
print_usage();
exit(EXIT_USAGE_ERROR);
}
if (options->usePipe && !options->argsFile && !foundTripleColon) {
// Can't read from stdin if --pipe is specified
print_usage();
exit(EXIT_USAGE_ERROR);
}
if (options->cmdCount > 0 && options->cmd[0][0] == '\0') {
print_usage();
exit(EXIT_USAGE_ERROR);
}
}
void free_options(Options* options) {
if (options->argsFile) {
free(options->argsFile);
}
if (options->cmd) {
for (int i = 0; i < options->cmdCount; i++) {
free(options->cmd[i]);
}
free(options->cmd);
}
if (options->perTaskArgs) {
for (int i = 0; i < options->perTaskArgsCount; i++) {
free(options->perTaskArgs[i]);
}
free(options->perTaskArgs);
}
}
void free_task(Task* task) {
if (task->args) {
for (int i = 0; i < task->argCount; i++) {
free(task->args[i]);
}
free(task->args);
}
}
void free_tasks(Task** tasks, int taskCount) {
if(tasks){
for (int i = 0; i < taskCount; i++) {
if (tasks[i]) {
free_task(tasks[i]);
free(tasks[i]);
}
}
free(tasks);
}
}
void print_task(int jobNum, Task* task, bool isPipe) {
printf("%d: ", jobNum);
for (int i = 0; i < task->argCount; i++) {
bool hasSpace = false;
for (int j = 0; task->args[i][j] != '\0'; j++) {
if (task->args[i][j] == ' ') {
hasSpace = true;
break;
}
}
if (hasSpace) {
printf("\"%s\"", task->args[i]);
}
else {
printf("%s", task->args[i]);
}
// Add space if not the last argument
if (i < task->argCount - 1) {
printf(" ");
}
}
if (isPipe) {
printf(" |");
}
printf("\n");
}
//REF:edSTEM week 7
void read_args_from_file(Options* options, Task*** tasks, int* taskCount)
{
FILE* file = fopen(options->argsFile, "r");
if (!file) {
fprintf(stderr, "uqparallel: unable to open %s\n", options->argsFile);
exit(EXIT_USAGE_ERROR);
}
char* line = NULL;
size_t len = 0;
ssize_t read;
// Count lines first to allocate tasks array
*taskCount = 0;
while ((read = getline(&line, &len, file)) != -1) {
if (read <= 1 && options->cmdCount == 0) {
continue;
}
(*taskCount)++;
}
if (fseek(file, 0, SEEK_SET) != 0) {
fprintf(stderr, "uqparallel: Error seeking in file\n");
fclose(file);
free(line);
exit(EXIT_FAILURE);
}
//REF: chatGPT help me to add this
//handle case of no tasks
if (*taskCount == 0) {
free(line);
fclose(file);
*tasks = NULL;
return;
}
// Allocate tasks array
*tasks = malloc(*taskCount * sizeof(Task*));
if (!*tasks) {
fprintf(stderr, "Memory allocation failed\n");
free(line);
fclose(file);
exit(EXIT_FAILURE);
}
for (int i = 0; i < *taskCount; i++) {
(*tasks)[i] = malloc(sizeof(Task));
if (!(*tasks)[i]) {
fprintf(stderr, "Memory allocation failed\n");
for (int j = 0; j < i; j++) {
free((*tasks)[j]);
}
free(*tasks);
free(line);
fclose(file);
exit(EXIT_FAILURE);
}
(*tasks)[i]->args = NULL;
(*tasks)[i]->argCount = 0;
(*tasks)[i]->pid = -1;
(*tasks)[i]->status = 0;
(*tasks)[i]->completed = false;
}
// Read file again to fill tasks
int taskIndex = 0;
while ((read = getline(&line, &len, file)) != -1)
{
// Remove newline if present
if (read > 0 && line[read - 1] == '\n') {
line[read - 1] = '\0';
read--;
}
if (read == 0 && options->cmdCount == 0) {
continue;
}
int numTokens;
char** lineArgs = split_space_not_quote(line, &numTokens);
if (!lineArgs) {
fprintf(stderr, "Error parsing line\n");
continue;
}
// Create the task's argument list
if (options->cmdCount > 0) {
// Command is provided on command line
(*tasks)[taskIndex]->argCount = options->cmdCount + numTokens;
(*tasks)[taskIndex]->args = (char**) malloc((*tasks)[taskIndex]->argCount * sizeof(char*));
if (!(*tasks)[taskIndex]->args) {
fprintf(stderr, "Memory allocation failed\n");
for (int j = 0; j < numTokens; j++) {
free((*tasks)[j]);
}
free(*tasks);
free(line);
fclose(file);
exit(EXIT_FAILURE);
}
// Copy command and fixed args
for (int i = 0; i < options->cmdCount; i++) {
(*tasks)[taskIndex]->args[i] = strdup(options->cmd[i]);
}
for (int i = 0; i < numTokens; i++) {
(*tasks)[taskIndex]->args[options->cmdCount + i] =
strdup(lineArgs[i]);
}
}
else {
(*tasks)[taskIndex]->argCount = numTokens;
(*tasks)[taskIndex]->args =
(char**)malloc(numTokens * sizeof(char*));
if (!(*tasks)[taskIndex]->args) {
fprintf(stderr, "Memory allocation failed\n");
for (int i = 0; i < numTokens; i++) {
free(lineArgs[i]);
}
free(lineArgs);
free(line);
fclose(file);
exit(EXIT_FAILURE);
}
// Copy line args
for (int i = 0; i < numTokens; i++) {
(*tasks)[taskIndex]->args[i] =
strdup(lineArgs[i]);
}
}
// Free the parsed line arguments
for (int i = 0; i < numTokens; i++) {
free(lineArgs[i]);
}
free(lineArgs);
taskIndex++;
}
free(line);
fclose(file);
}
//REF:edSTEM week 7
void read_args_from_stdin(Options* options, Task*** tasks, int* taskCount) {
char* line = NULL;
size_t len = 0;
ssize_t read;
// Allocate tasks array dynamically
int capacity = 10;
*tasks = malloc(capacity * sizeof(Task*));
if (!*tasks) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
*taskCount = 0;
while ((read = getline(&line, &len, stdin)) != -1) {
// Remove newline if present
if (read > 0 && line[read - 1] == '\n') {
line[read - 1] = '\0';
read--;
}
// Skip empty lines if no command provided
if (read == 0 && options->cmdCount == 0) {
continue;
}
// Resize tasks array if needed
if (*taskCount >= capacity) {
capacity *= 2;
Task** newTasks = realloc(*tasks, capacity * sizeof(Task*));
if (!newTasks) {
perror("Failed to realloc tasks array");
free(line);
free_tasks(*tasks, *taskCount);
exit(EXIT_FAILURE);
}
*tasks = newTasks;
}
// Allocate new task
(*tasks)[*taskCount] = malloc(sizeof(Task));
if (!(*tasks)[*taskCount]) {
fprintf(stderr, "Memory allocation failed\n");
free(line);
free_tasks(*tasks, *taskCount);
exit(EXIT_FAILURE);
}
(*tasks)[*taskCount]->args = NULL;
(*tasks)[*taskCount]->argCount = 0;
(*tasks)[*taskCount]->pid = -1;
(*tasks)[*taskCount]->status = 0;
(*tasks)[*taskCount]->completed = false;
int numTokens;
char** lineArgs = split_space_not_quote(line, &numTokens);
if (!lineArgs) {
fprintf(stderr, "Error parsing line\n");
free((*tasks)[*taskCount]);
continue;
}
if (options->cmdCount > 0) {
(*tasks)[*taskCount]->argCount = options->cmdCount + numTokens;
(*tasks)[*taskCount]->args =
malloc((*tasks)[*taskCount]->argCount * sizeof(char*));
if (!(*tasks)[*taskCount]->args) {
fprintf(stderr, "Memory allocation failed\n");
for (int i = 0; i < numTokens; i++) {
free(lineArgs[i]);
}
free(lineArgs);
free(line);
free((*tasks)[*taskCount]);
free_tasks(*tasks, *taskCount);
exit(EXIT_FAILURE);
}
for (int i = 0; i < options->cmdCount; i++) {
(*tasks)[*taskCount]->args[i] = strdup(options->cmd[i]);
}
for (int i = 0; i < numTokens; i++) {
(*tasks)[*taskCount]->args[options->cmdCount + i] =
strdup(lineArgs[i]);
}
}
else {
// Command is from stdin
(*tasks)[*taskCount]->argCount = numTokens;
(*tasks)[*taskCount]->args = malloc(numTokens * sizeof(char*));
if (!(*tasks)[*taskCount]->args) {
fprintf(stderr, "Memory allocation failed\n");
for (int i = 0; i < numTokens; i++) {
free(lineArgs[i]);
}
free(lineArgs);
free(line);
free((*tasks)[*taskCount]);
free_tasks(*tasks, *taskCount);
exit(EXIT_FAILURE);
}
for (int i = 0; i < numTokens; i++) {
(*tasks)[*taskCount]->args[i] = strdup(lineArgs[i]);
}
}
for (int i = 0; i < numTokens; i++) {
free(lineArgs[i]);
}
free(lineArgs);
(*taskCount)++;
}
free(line);
//REF: chatGPT help me add this condition
// If no tasks were read, handle appropriately
if (*taskCount == 0) {
free(*tasks);
*tasks = NULL;
}
}
void create_tasks_from_cmdline(Options* options, Task*** tasks, int* taskCount)
{
*taskCount = options->perTaskArgsCount;
if (*taskCount == 0) {
*tasks = NULL;
return;
}
*tasks = malloc(*taskCount * sizeof(Task*));
if (!*tasks) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < *taskCount; i++) {
(*tasks)[i] = malloc(sizeof(Task));
if (!(*tasks)[i]) {
fprintf(stderr, "Memory allocation failed\n");
for (int j = 0; j < i; j++) {
free_task((*tasks)[j]);
free((*tasks)[j]);
}
free(*tasks);
exit(EXIT_FAILURE);
}
(*tasks)[i]->pid = -1;
(*tasks)[i]->status = 0;
(*tasks)[i]->completed = false;
// Set up args array
(*tasks)[i]->argCount = options->cmdCount + 1;
(*tasks)[i]->args = malloc((*tasks)[i]->argCount * sizeof(char*));
// Copy command and fixed args
for (int j = 0; j < options->cmdCount; j++) {
(*tasks)[i]->args[j] = strdup(options->cmd[j]);
}
(*tasks)[i]->args[options->cmdCount] = strdup(options->perTaskArgs[i]);
}
}
void execute_task(Task* task, int stdinFd, int stdoutFd)
{
if (task->argCount == 0 || task->args[0][0] == '\0') {
fprintf(stderr, "uqparallel: can't execute empty command\n");
task->status = EXIT_EMPTY_COMMAND;
task->completed = true;
return;
}
//Fork a child process
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
if (stdinFd != STDIN_FILENO) {
dup2(stdinFd, STDIN_FILENO);
close(stdinFd);
}
if (stdoutFd != STDOUT_FILENO) {
dup2(stdoutFd, STDOUT_FILENO);
close(stdoutFd);
}
for (int i = 3; i < 256; i++) {
close(i);
}
execvp(task->args[0], task->args);
fprintf(stderr, "uqparallel: \"%s\" can't be executed\n", task->args[0]);
raise(SIGUSR1);
// Should not reach here, but just in case
exit(EXIT_FAILURE);
}
else {
// Parent process
task->pid = pid;
}
}
bool reap_tasks(Task** tasks, int taskCount, bool waitForAll) {
bool anyFailed = false;
int status;
pid_t pid;
while ((pid = waitpid(-1, &status, waitForAll ? 0 : WNOHANG)) > 0) {
// Find the task with this pid
for (int i = 0; i < taskCount; i++) {
if (tasks[i]->pid == pid) {
tasks[i]->status = status;
tasks[i]->completed = true;
// Check if the task failed
if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
anyFailed = true;
} else if (WIFSIGNALED(status)) {
anyFailed = true;
}
break;
}
}
}
return anyFailed;
}
void terminate_tasks(Task** tasks, int taskCount, int signal) {
for (int i = 0; i < taskCount; i++) {
if (tasks[i]->pid > 0 && !tasks[i]->completed) {
kill(tasks[i]->pid, signal);
}
}
}
int count_running_tasks(Task** tasks, int taskCount) {
int count = 0;
for (int i = 0; i < taskCount; i++) {
if (tasks[i]->pid > 0 && !tasks[i]->completed) {
count++;
}
}
return count;
}
void wait_for_one_second(void) {
sigset_t mask;
struct timespec timeout;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
timeout.tv_sec = 1;
timeout.tv_nsec = 0;
sigtimedwait(&mask, NULL, &timeout);
}
void execute_pipeline(Options* options, Task** tasks, int taskCount) {
(void)options;
if (taskCount == 0) {
return;
}
if (taskCount == 1) {
execute_task(tasks[0], STDIN_FILENO, STDOUT_FILENO);
int status;
waitpid(tasks[0]->pid, &status, 0);
tasks[0]->status = status;
tasks[0]->completed = true;
return;
}
int pipes[taskCount - 1][2];
for (int i = 0; i < taskCount - 1; i++) {
if (pipe(pipes[i]) == -1) {
perror("pipe creation failed");
exit(EXIT_FAILURE);
}
}
execute_task(tasks[0], STDIN_FILENO, pipes[0][1]);
close(pipes[0][1]);
for (int i = 1; i < taskCount - 1; i++) {
execute_task(tasks[i], pipes[i-1][0], pipes[i][1]);
close(pipes[i-1][0]);
close(pipes[i][1]);
}
execute_task(tasks[taskCount - 1], pipes[taskCount - 2][0], STDOUT_FILENO);
close(pipes[taskCount - 2][0]);
for (int i = 0; i < taskCount; i++) {
if (tasks[i]->pid <= 0) {
continue;
}
int status;
waitpid(tasks[i]->pid, &status, 0);
tasks[i]->status = status;
tasks[i]->completed = true;
}
}
//REF:edSTEM week 6
void execute_tasks(Options* options)
{
Task** tasks = NULL;
int taskCount = 0;
//creat tasks based on input source
if (options->perTaskArgs != NULL) {
create_tasks_from_cmdline(options, &tasks, &taskCount);//arguments from command line
}
else if (options->argsFile != NULL) {
read_args_from_file(options, &tasks, &taskCount);//arguments from file
}
else{
read_args_from_stdin(options, &tasks, &taskCount);//arguments from stdin
}
if (taskCount == 0) {
if (tasks) {
free(tasks);
}
exit(EXIT_EMPTY_COMMAND);
}
if (options->printOnly) {
for (int i = 0; i < taskCount; i++) {
print_task(i + 1, tasks[i], options->usePipe && i < taskCount - 1);
}
free_tasks(tasks, taskCount);
return;
}
if (options->usePipe) {
// Execute as pipeline
execute_pipeline(options, tasks, taskCount);
//REF:chatGPT help me to recode this part
// For pipelines, we need to exit with appropriate status
int exitStatus = 0;
// Find the exit status of the last task
for (int i = 0; i < taskCount; i++) {
if (tasks[i]->completed) {
if (WIFEXITED(tasks[i]->status)) {
exitStatus = WEXITSTATUS(tasks[i]->status);
} else if (WIFSIGNALED(tasks[i]->status)) {
exitStatus = EXIT_SIGNAL_TERMINATION;
}
}
}
// Free tasks
free_tasks(tasks, taskCount);
// Exit with appropriate status
exit(exitStatus);
}
else {
// Execute tasks in parallel
int runningTasks = 0;
int nextTask = 0;
bool anyFailed = false;
while (nextTask < taskCount || runningTasks > 0)
{
// Start tasks if possible
while (nextTask < taskCount &&
runningTasks < options->maxJobs &&
!interrupted &&
!(anyFailed && options->abortOnError))
{
execute_task(tasks[nextTask], STDIN_FILENO, STDOUT_FILENO);
if (tasks[nextTask]->pid > 0)
{
runningTasks++;
}
nextTask++;
}
anyFailed = reap_tasks(tasks, taskCount, false);
// Update running task count
runningTasks = count_running_tasks(tasks, taskCount);
// Handle abort conditions
if ((anyFailed && options->abortOnError) || interrupted)
{
if (runningTasks > 0)
{
// Send SIGTERM or SIGINT to running tasks
terminate_tasks(tasks, taskCount,
interrupted ? SIGINT : SIGTERM);
// Wait up to one second for tasks to terminate
wait_for_one_second();
reap_tasks(tasks, taskCount, false);
runningTasks = count_running_tasks(tasks, taskCount);
if (runningTasks > 0)
{
terminate_tasks(tasks, taskCount, SIGKILL);
reap_tasks(tasks, taskCount, true);
}
}
if (nextTask < taskCount || runningTasks > 0)
{
if (interrupted) {
fprintf(stderr,
"uqparallel: aborting due to interruption\n");
}
else {
fprintf(stderr,
"uqparallel: execution failure - aborting\n");
}
}
// Free tasks
free_tasks(tasks, taskCount);
// Exit with appropriate status
if (interrupted) {
exit(EXIT_INTERRUPTED);
}
else {
// Get the status of the task that failed
for (int i = 0; i < taskCount; i++) {
if (tasks[i]->completed) {
if (WIFEXITED(tasks[i]->status)) {
int status = WEXITSTATUS(tasks[i]->status);
if (status != 0) {
exit(status);
}
} else if (WIFSIGNALED(tasks[i]->status)) {
exit(EXIT_SIGNAL_TERMINATION);
}
}
}
exit(1); // Default error exit code
}
}
}
// Exit with status of last command if we get here
int exitStatus = 0;
//REF:charGPT help me recode the exit status part
// Find the exit status of the last task
for (int i = taskCount - 1; i >= 0; i--) {
if (tasks[i]->completed) {
if (WIFEXITED(tasks[i]->status)) {
exitStatus = WEXITSTATUS(tasks[i]->status);
} else if (WIFSIGNALED(tasks[i]->status)) {
exitStatus = EXIT_SIGNAL_TERMINATION;
}
break;
}
}
free_tasks(tasks, taskCount);
exit(exitStatus);
}
}