title: fd leak, custom Shell
body: <p>I'm working on a custom shell that can handle multiple pipes. But every time I execute a new pipeline and check the process with <code>ls -l /proc/pid/fd</code> I get something like in the picture below and the list keeps expanding with every new pipeline executed:</p>
  
  <p><a href="https://i.stack.imgur.com/dwkLa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dwkLa.png" alt="screenshot of terminal"></a></p>
  
  <p>Question: Is this considered as a fd leak? And how do I fix it?</p>
  
  <p>Here's a code snippet for my pipeline execution:</p>
  
  <pre><code>enum PIPES {READ, WRITE};
  
  void execute_pipeline(char*** pipeline)
  {
      int fd[2];
      int fd_backup = 0;
      pid_t child_pid;
  
      while (*pipeline != '\0')
      {
          pipe(fd);
          child_pid = fork();
  
          if(child_pid == -1)
          {
              perror("fork");
              exit(1);
          }
          else if(child_pid == 0)
          {
              dup2(fd_backup, 0);// (old, new)
              close(fd[READ]);
  
              if(*(pipeline + 1) != '\0')
              {
                  dup2(fd[WRITE], 1);
              }
              execvp((*pipeline)[0], *pipeline);
              exit(1);
          }
          else// Parent process
          {
              wait(NULL);
              close(fd[WRITE]);
              fd_backup = fd[READ];
              pipeline++;
          }
      }
  }
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>An example how to call execute_pipeline:</p>
  
  <pre><code>char *ls[] = {"ls", "-l", NULL};
  char *sort[] = {"sort", "-r", NULL};
  char *head[] = {"head", "-n", "3", NULL};
  char **pipeline[] = {ls, sort, head, NULL};
  
  execute_pipeline(pipeline);
  </code></pre>