title: C - WHILE Loop with fork() / pipe() inside
body: <p>I have a problem where I must implement a key logger into a shell we have made in class. I am having trouble getting the flow of the program within a while loop to continue looping after a child process is created and it has ran execlp(). </p>
  
  <p>Here is a simple program I have made to work on the part I am having trouble with.. My main program, pipe.c, includes the parent/child process with a while loop that "should" continue getting an input from the user with fgets(), create a child process, use dup2(), write to stdout, then the child process invoke the receive.c executable which will get the input from stdin and display it.. </p>
  
  <pre><code>/* file: pipe.c */
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  
  int main() {
    int key_logger_on = 0;
    int p[2];
    pid_t pid;
    char str[256];
    char input[1024];
    int status;
    char * file = "test.txt";
  
    printf("Input :: ");
    while(fgets(input, sizeof(input), stdin)) {
  
      if (pipe(p)==-1) {
        perror("Pipe create error");
        exit(1);
      }
  
      if ((pid=fork())==-1) {
        perror("Fork create error");
        exit(1);
      }
  
      if (pid==0) {
        close(p[1]);  // Close write
        dup2(p[0],0);
        close(p[0]);
        execlp("receive",file,NULL);
     }
  
      else {
        close(p[0]);  // Close read
        fflush(stdout);
        dup2(p[1],1);
        close(p[1]);
        write(1, input, strlen(input)+1);
        waitpid(pid, NULL, 0);
      }
      printf("Input :: ");
    }
  }
  </code></pre>
  
  <p>Here is the simple receive.c that gets the stdin of the input and displays it. The file is just a test of passing a parameter.</p>
  
  <pre><code>/* file: receive.c */
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(int argc, char *argv[]) {
    char input[256];
    fgets(input, sizeof(input), stdin);
    printf("FILE: %s  RECEIVE: %s", argv[0],input);
    return 0;
  }
  </code></pre>
  
  <p>Right now, all this does for me is when ran the first time, it gets the input, sends it to stdout, child calls receive, prints out the input, and then the whole parent program exits, the while loop is ignored, everything just ends. I'm very new to forks and pipes so this is very frustrating to deal with! Even made me post a question on here for the first time! Thank you very much in advance. </p>