title: Using pipe to pass data between two processes continuously
body: <p>I'm trying to make two child process to communicate with each other via a pipe.</p>
  
  <p>One child is supposed to keep reading from stdin, passing what it read to the pipe, while the other child is supposed to read from the pipe and print that to stdout.</p>
  
  <p>I manage to get it to work, but only once, in the second iteration after reading a number, I get: <code>write failed: Bad file descriptor</code>.</p>
  
  <p>I can't figure out what am I doing wrong...</p>
  
  <pre><code>#define READ 0
  #define WRITE 1
  int main(){
  
      int pipe_descs[2];
      int retval = pipe(pipe_descs);
      int pid = fork();
      if(pid == 0){   //son that reads from stdin and writes to pipe 
          close(pipe_descs[READ]);
          int x;
          while(1){
              open(pipe_descs[WRITE]);
              scanf("%d", &amp;x);
              if(write(pipe_descs[WRITE], &amp;x, sizeof(int)) != sizeof(int)){
                  perror("write failed");
                  exit(EXIT_FAILURE);
              }
              close(pipe_descs[WRITE]);
          }
          perror("");
      }
      else if(pid &gt; 0){   //parent
  
          int pid = fork();
          if(pid == 0){   //son that reads from pipe and write to stdout 
              int pipestat;
              int readNum;
              close(pipe_descs[WRITE]);
              while((pipestat = read(pipe_descs[READ], &amp;readNum, sizeof(int))) &gt; 0){
  
                  printf("read: %d \n", readNum);
                  //close(pipe_descs[READ]);
                  //open(pipe_descs[READ]);
              }
              if (pipestat==-1) {
                  perror("");
                  fprintf(stderr, "error to pipe... exiting\n");
                  exit(EXIT_FAILURE);
              }
          }
      }
  
      int status;
      int i = 2;
      while (i &gt; 0){
          wait(&amp;status);
          i--;
      }
  }
  </code></pre>