Advertisement
Guest User

Untitled

a guest
Jan 16th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.85 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <unistd.h>
  5. #include <sys/wait.h>
  6.  
  7. /* Beachten Sie den geaenderten Prototypen von main()! Referenz: man 2 execve */
  8. /*dup2 statt dudup2 statt dupp, Fehlerabfrage, & abfangen was passiert, wenn man gar keine argumente angibt*/
  9.  
  10. int main(int argc, char *argv[], char *envp[])
  11. {
  12.     int pid1, pid2;
  13.     int status1, status2;
  14.     int pipefds[2];
  15.  
  16.     if (argc != 3)
  17.     {
  18.         printf("Falsche Anzahl der Argumente (nicht 3).\n");
  19.         exit(EXIT_FAILURE);
  20.     }
  21.  
  22.     if (pipe(pipefds) < 0)
  23.     {
  24.         perror("Fehler bei pipe().\n");
  25.         exit(EXIT_FAILURE);
  26.     }
  27.  
  28.     pid1 = fork();
  29.     if(pid1 < 0)
  30.     {
  31.         perror("fork()");
  32.         exit(EXIT_FAILURE);
  33.     }
  34.     else if(!pid1)
  35.     {
  36.     /*child1*/
  37.         if(dup2(pipefds[1], 1) < 0)     //pipefds[0] ist lese-ende, 1 ist schreib-ende?
  38.         {
  39.             perror("Fehler bei dup2 bei Child1.\n");
  40.             exit(EXIT_FAILURE);
  41.         }
  42.         if(close(pipefds[0]) < 0)
  43.         {
  44.             perror("Fehler bei close() in Child1.\n");
  45.             exit(EXIT_FAILURE);
  46.         }
  47.         char *argv1[] = { "/bin/ls", "-la", argv[1], NULL};
  48.         execve(argv1[0], argv1, envp);
  49.         perror("execve()");
  50.         exit(EXIT_FAILURE);
  51.     }
  52.  
  53.     pid2 = fork();
  54.     if(pid2 <0)
  55.     {
  56.         perror("fork()");
  57.         exit(EXIT_FAILURE);
  58.     }
  59.     else if(!pid2)
  60.     {
  61.         if(dup2(pipefds[0], 0) < 0)
  62.         {
  63.             perror("Fehler bei dup2 bei Child2.\n");
  64.             exit(EXIT_FAILURE);
  65.         }
  66.         if(close(pipefds[1]) < 0)
  67.         {
  68.             perror("Fehler bei close() bei Child2.\n");
  69.             exit(EXIT_FAILURE);
  70.         }
  71.         char *argv2[] = {"/bin/grep", argv[2], NULL};
  72.         execve(argv2[0], argv2, envp);
  73.         perror("execve()");
  74.         exit(EXIT_FAILURE);
  75.     }
  76.     if (close(pipefds[0]) < 0)
  77.     {
  78.         perror("Fehler bei close() bei Parent.\n");
  79.         exit(EXIT_FAILURE);
  80.     }
  81.     if (close(pipefds[1]) < 0)
  82.     {
  83.         perror("Fehler bei close() bei Parent.\n");
  84.         exit(EXIT_FAILURE);
  85.     }
  86.  
  87.     waitpid(pid1, &status1, 0);
  88.     waitpid(pid2, &status2, 0);
  89.  
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement