Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. #include <sys/wait.h>
  2. #include <zconf.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7.  
  8.  
  9.  
  10. #define CHILD_AMOUNT 2
  11.  
  12.  
  13.  
  14. int create_child() {
  15. int i;
  16. for(i=0;i<CHILD_AMOUNT;i++){
  17. pid_t pid = fork();
  18. if (pid== 0) {
  19. return i+1;
  20. } else if (pid > 0) {
  21. continue;
  22. } else {
  23. printf("Erro ao fazer fork\n");
  24. exit(-1);
  25. }
  26. }
  27. return 0;
  28. }
  29.  
  30. void close_descriptor(int descriptor) {
  31. if (close(descriptor) == -1) {
  32. printf("Nao foi possivel fechar o pipe %d\n", descriptor);
  33. exit(-1);
  34. }
  35. }
  36.  
  37.  
  38. int main(int argc) {
  39. int fd1[2],fd2[2],id;
  40.  
  41. if (pipe(fd1) == -1) {
  42. printf("Erro ao criar o pipe\n");
  43. exit(-1);
  44. }
  45. if (pipe(fd2) == -1) {
  46. printf("Erro ao criar o pipe\n");
  47. exit(-1);
  48. }
  49.  
  50. id=create_child();
  51.  
  52. if(id==0){
  53. close_descriptor(fd1[0]);
  54. dup2(fd1[1],1);
  55. execlp("ls","ls","-la",(char*)NULL);
  56. exit(-1);
  57. }else if(id==1){
  58. close_descriptor(fd1[1]);
  59. close_descriptor(fd2[0]);
  60. dup2(fd1[0],0);
  61. dup2(fd2[1],1);
  62. sleep(1);
  63. execlp("sort","sort",(char*)NULL);
  64. exit(-1);
  65. }else{
  66. close_descriptor(fd2[1]);
  67. dup2(fd2[0],0);
  68. sleep(2);
  69. execlp("wc","wc","-l",(char*)NULL);
  70. exit(-1);
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement