Advertisement
Guest User

Dynpipe_waitpidhang

a guest
Apr 8th, 2017
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <fcntl.h>
  4. #include <sys/file.h>
  5. #include <unistd.h>
  6. #include <sys/wait.h>
  7. #include <string.h>
  8.  
  9. #define WRITE 1
  10. #define READ 0
  11.  
  12. void  parse(char *line, char **argv) {
  13.     while (*line != '\0') {
  14.         while (*line == ' ') {
  15.             *line = '\0';
  16.             line++;
  17.         }
  18.         *argv = line;
  19.         argv++;
  20.         while (!(*line == '\0' || *line == ' ')) {
  21.             line++;
  22.         }
  23.     }
  24.     *argv = '\0';        
  25. }
  26.  
  27. void genArgs(char* args[5][9], int, char**);
  28.  
  29. int main(int argc, char** argv) {
  30.     if (argc < 3 || argc > 6) {
  31.         printf("Please enter between two and five arguments.\n");
  32.         return(1);
  33.     }
  34.     int cmds[argc - 2][2];
  35.     int pids[5];
  36.     char *args[5][9];
  37.     genArgs(args, argc, argv);
  38.     argc = argc - 1;
  39.  
  40.     for (int i = 0; i < argc; i++) {   
  41.         pipe(cmds[i]);
  42.         if ((pids[i] = fork()) == 0) {
  43.             if (i > 0 && i < argc - 1) {
  44.                 dup2(cmds[i - 1][READ], READ);
  45.                 dup2(cmds[i][WRITE], WRITE);
  46.             }
  47.             else if (i == argc - 1) {
  48.                 dup2(cmds[i - 1][READ], READ);
  49.             }
  50.             else {
  51.                 dup2(cmds[i][WRITE], WRITE);
  52.             }
  53.             for (int j = 0; j <= i; j++) {
  54.                 close(cmds[j][READ]);
  55.                 close(cmds[j][WRITE]);
  56.             }
  57.             execvp(*args[i], args[i]);
  58.             return(1);
  59.         }
  60.         close(cmds[i][WRITE]);
  61.         //close(cmds[i][READ]); uncommenting this line will result in waitpid() to hang if
  62.                                 //program is executed with an argument that requires reading and writing:
  63.                                 //./Dynpipe "ls -l" "grep cpp" "wc -l"
  64.     }
  65.     for (int i = 0; i < argc; i++) {
  66.         int status;
  67.         waitpid(pids[i], &status, 0);
  68.     }
  69.     return(0);
  70. }
  71.  
  72. void genArgs(char* args[5][9], int count, char** input) {
  73.     for (int i = 1; i < count; i++) {
  74.         parse(input[i], args[i - 1]);
  75.     }  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement