anutka

Untitled

Mar 10th, 2021
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4.  
  5. int main(int argc, char* argv[]) {
  6.  
  7. int pipefd[argc - 2][2];
  8. for (int i = 0; i < argc - 1; i++) {
  9. pipe(pipefd[i]);
  10. }
  11.  
  12. pid_t childs[argc - 1];
  13. for (int i = 1; i < argc; i++) {
  14. char* cmd = argv[i];
  15. childs[i-1] = fork();
  16. if (childs[i-1] == 0) {
  17. if (i-2 >= 0) {
  18. close(pipefd[i-2][1]);
  19. dup2(pipefd[i-2][0], 0);
  20. close(pipefd[i-2][0]);
  21. }
  22. if (i-1 <= argc-3) {
  23. close(pipefd[i-1][0]);
  24. dup2(pipefd[i-1][1], 1);
  25. close(pipefd[i-1][1]);
  26. }
  27. execlp(cmd, cmd, NULL);
  28. return 1;
  29. } else {
  30. close(pipefd[i-2][1]);
  31. close(pipefd[i-2][0]);
  32. }
  33. }
  34.  
  35. for (int i = 0; i < argc-1; i++) {
  36. waitpid(childs[i], NULL, 0);
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment