title: How to get data from read program to main program using execve and pipe?
body: <p>I am doing a project in that I have to create a child process by using fork and then parent process tells to child process to execute another C program "read.c"(which reads all integers from a .txt ﬁle and compute average) by using execve then I have to send that average value to parent process through pipe. I don't know how to get "average value" the result of the "read.c" program in child process of "process.c" program. Some of may friends said that I have to pass file descriptor useful for pipe(pfd[2]) into execve and from other program(read.c) i have to use pipe to write data to process.c program. but i don't know how to do that so it is not working properly. I am posting my codes for both process.c and read.c and please tell me which changes I should make to make it perform well.</p>
  
  <p>process.c</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;unistd.h&gt;
  #include&lt;stdlib.h&gt;
  
  main()
  {
  
      int pid;
      int pfd[2];
      int i;
      char string1[12];
      snprintf(string1,12,"%i",pfd[1]);
  
      char *args[] = {"read",&amp;string1[0],NULL};
  
      pipe(pfd);
      pid = fork();
  
      if(pid == 0)
      {
  
          execve("read",args,NULL);
  
          int size = 100;
          char buf[size]; 
  
          close(pfd[1]);
          read(pfd[0],buf,size);
          printf("%s\n",buf);
  
      }
  
  }
  </code></pre>
  
  <p>read.c</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;unistd.h&gt;
  #include&lt;stdlib.h&gt;
  
  
  int main (int argc,char *argv[],char *envp[])
  {
  
      int pfd[2];
      pfd[1]= atoi(argv[1]); 
      close(pfd[0]);
  
      FILE *ptr_file;
      char buf[1000];
      int sum = 0;
      int avg =0;
      int no = 0;
      int count = 0;
  
      ptr_file =fopen("data.txt","r");
      if (!ptr_file)
          return 1;
  
      while (fgets(buf,1000, ptr_file)!=NULL)
      {
          printf(" %s \n",buf);
          no = atoi(buf);
          sum = sum + no;
          printf("Sum = %d \n", sum);
          count++;
      }
  
      fclose(ptr_file);
      avg = sum/count;
      printf("Average : %d \n",avg);
      write(pfd[1],"hello",6);/*i just write here hello to see that it is working or not*/
      return 0;
  } 
  </code></pre>
  
  <p>If you have any solution to get output from read.c file to child process of process.c then please tell me.</p>