Advertisement
elfokd

Untitled

Dec 15th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.29 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <wait.h>
  5. #include <string.h>
  6. #include <limits.h>
  7.  
  8. enum
  9. {
  10.     P_LEN = 5,
  11. };
  12.  
  13. int
  14. main(int argc, char **argv)
  15. {
  16.     if (argc <= 2) {
  17.         return 0;
  18.     }
  19.  
  20.     char *sep = argv[1];
  21.     for (int i = 2; i < argc; ++i) {
  22.         if (!strcmp(sep, argv[i])) {
  23.             argv[i] = NULL;
  24.         }
  25.     }
  26.     argv[1] = NULL;
  27.  
  28.     for (int i = argc - 1; i > 1;) {
  29.         int j = i;
  30.         while (argv[j]) {
  31.             --j;
  32.         }
  33.         ++j;
  34.         int arg_cnt = i - j;
  35.         char **args;
  36.  
  37.         pid_t pid = fork();
  38.         if (pid < 0) {
  39.             _exit(1);
  40.         } else if (!pid) {
  41.             char *fname = argv[j];
  42.             args = calloc(arg_cnt + 2, sizeof(*args));
  43.             if (!args) {
  44.                 _exit(1);
  45.             }
  46.             args[0] = fname;
  47.             for (int k = 1; k <= arg_cnt; ++k) {
  48.                 args[k] = argv[k + j];
  49.             }
  50.             args[arg_cnt + 1] = NULL;
  51.             execvp(fname, args);
  52.             _exit(1);
  53.         } else {
  54.             int status;
  55.             wait(&status);
  56.             if (!WIFEXITED(status) || WEXITSTATUS(status)) {
  57.                 exit(1);
  58.             }
  59.             i = j - 2;
  60.         }
  61.     }
  62.  
  63.     exit(0);
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement