/**
 * Name    : Edison Chindrawaly
 * Class   : CSCI 4540 Spring 2001
 * Project : Using trapezoid rule to approximate the intergral of
 *           f(x) = 1/(x+1) for the interval [0,2]
 * Solution: h is the width of the trapezoid.
 *           h = (b-a)/n where n is the number of trapezoids.
 *           a and b is the interval to evaluate.
 *           T = h/2 * (y0 + 2y1 + 2y2 + 2y(n-1) + yn)
 *           Where y0...yn is the function of x -> f(x)
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <signal.h>

#define STDIN 0
#define STDOUT 1
#define READ 0
#define WRITE 1

void main()
{
 int pid_p=0,pid_c=0;
 int fd[2];
 float rec=0,n1=0;
 float tmp_result=0.0;
 float tmp_result2=0.0;
 float result = 0.0;
 float rec2=0.0;
 float y1=0.0,y2=2.0;
 float h=0;  // height of trapezoid
 int n = 64; // number of trapezoid

 if(pipe(fd)<0)
 {
  printf("ERROR: pipe failed\n");
  exit(0);
 }
 printf("Start simulation\n");

 h = (y2-y1)/n; // to get the width
 n1 = y1;  // n1 is the interval

 for(int i=1;i<n;i++)
 {
   if(fork() == 0) // child
   {
    pid_c = getpid();
    read(fd[READ],&rec,sizeof(rec));
    close(fd[READ]);
    tmp_result2=2.0*(1/(1+rec));
    write(fd[WRITE],&tmp_result2,sizeof(tmp_result2));
    write(fd[WRITE],&pid_c,sizeof(pid_c));
    close(fd[WRITE]);
    exit(0);
   }
   else // parent
   {
    pid_p = getpid();
    n1+=h;          // add the interval 1/n1 + 1/n2
    write(fd[WRITE],&n1,sizeof(n1));
    wait(&pid_c);   // wait for child
    read(fd[READ], &rec2, sizeof(rec2));
    read(fd[READ], &pid_c, sizeof(pid_c));
    printf("Receive tmp_result from child of %d : %.2f\n",pid_c,rec2);
    tmp_result+=rec2;
   } // end of parent
 } // end of for-loop

 close(fd[READ]);
 close(fd[WRITE]);
 result=(h/2)*((1/(y1+1))+tmp_result+(1/(y2+1)));
 printf("Final result : %.2f\n",result);
}
 

1