title: How to prevent garbage being read from read end of PIPE in Linux
body: <p>I have written a small code using pipe and fork. The child process calls child function which writes to the pipe. The parent process calls parent function which reads from the pipe. </p>
  
  <p>The problem comes when the first call of the program after fork() goes to parent function. Here the write end is closed. Now the problem is that the read call is reading some garbage into buf and nread is giving value > 0 . How can this be prevented.</p>
  
  <p>Using Linux 2.6.32-30-generic and gcc 4.4.3. Below is the code::</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;unistd.h&gt;
  
  #define MSGSIZE 16
  
  void parent(int* p);
  void child(int* p);
  
  char* msg1 = "hello";
  char* msg2 = "bye";
  
  int main()
  {
      int pfd[2];
      if(pipe(pfd) == -1)
      {
          printf("Unable to create pipe\n");
          exit(1);
      }
      fcntl(pfd[0],F_SETFL,O_NDELAY);
  
      if(fork() == 0)
          child(pfd);
      else
          parent(pfd);
  
      return 0;
  }
  
  void parent(int p[2])
  {
      int nread;
      char buf[MSGSIZE];
      buf[0] = '\0';
  
      close(p[1]);
      for(;;)
      {
          nread = read(p[0] , buf , MSGSIZE);
          if(nread == 0)
          {
              printf("pipe Empty/n");
              sleep(1);
          }
          else
          {
              if(strcmp(buf,msg2) == 0)
              {
                  printf("End of conversation\n");
                  exit(0);
              }
              else
                  printf("MSG=%s\n" , buf);
          }
      }
  }
  
  void child(int p[2])
  {
      int count;
      close(p[0]);
      for(count = 0 ; count &lt; 3 ; count++)
      {
          write(p[1],msg1 , MSGSIZE);
          sleep(3);
      }
      write(p[1],msg2,MSGSIZE);
      exit(0);
  }
  </code></pre>