#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>

int main(int argc, char* argv[])
{
  int a=atoi(argv[1]);
  int i,pid,test,fds[2];
  pipe(fds);

  pid=fork();
  if(pid==0)
  {//b

      test = close(0); assert(test==0);
      read(fds[0],&pid,sizeof(int));
      pid+=pid;
      printf("Sum of pids: %d.\n", pid);
      test = close(fds[0]); assert(test==0);
      test = close(fds[1]); assert(test==0);
      sleep(1);
      exit(0);

  }system("ps -o pid,ppid,comm");
    for(i=0;i<a;i++){
        pid=fork();
        if(pid==0){//g
            test = close(1); assert(test==0);
            test = dup(fds[1]); assert(test==1);
            test = close(fds[0]); assert(test==0);
            test = close(fds[1]); assert(test==0);
            execlp("./g", "./g", NULL);
            fprintf(stderr,"execlp did not work\n");
            exit(1);

        }system("ps -o pid,ppid,comm");

    }
    wait(0);
    wait(0);
    system("ps -o pid,ppid,comm");




  return 0;
}

