Untitled
unknown
c_cpp
2 years ago
1.5 kB
3
Indexable
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s <command1> <command2> ... <commandN>\n", argv[0]); return 1; } int num_commands = argc - 1; printf("Num of commands: %d\n", num_commands); int status; pid_t pid; int child_index[num_commands]; for (int i = 0; i < num_commands; i++) { pid = fork(); if (pid == -1) { perror("Fork failed"); exit(1); } if (pid == 0) { // Child process execl(argv[i + 1], argv[i + 1], (char *)0); perror("Execl failed"); exit(1); } else { child_index[i] = pid; } } // Parent process for (int i = 0; i < num_commands; i++) { pid = wait(&status); // Print out success message to the corresponding command index for this child PID for (int j = 0; j < num_commands; j++) { if (child_index[j] == pid) { if (WIFEXITED(status) && WEXITSTATUS(status) == 0) { printf("Command %s has completed successfully\n", argv[j + 1]); } else { printf("Command %s has not completed successfully\n", argv[j + 1]); } break; } } } printf("All done, bye-bye!\n"); return 0; }
Editor is loading...