#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/types.h>

int main(int argc, char* argv[])
{
  int a=atoi(argv[1]);
  int i;int j;
  int in;
  int pid;
  int myPid;
  int pidSum = 0;
  int test;
  int fds[2];

  pipe(fds);

  printf("%d\n",a);
  
  pid=fork();
  if(pid==0){
    //b
    system("ps -o pid,ppid,comm");
    test = close(fds[1]);assert(test==0);
    while(a>0){
      read(fds[0],&in,sizeof(int));
      printf("g-process pid: %d\n",in);
      pidSum = pidSum + in;
      a--;
    }
    printf("pidSum: %d\n",pidSum);
    sleep(5);
    exit(0);
  }
  sleep(1);

  i = a;
  while(a>0){
    pid=fork();
    if(pid==0){
      //g
      system("ps -o pid,ppid,comm");
      test = close(1);assert(test==0);
      dup(fds[1]);
      test = close(fds[1]);assert(test==0);
      test = close(fds[0]);assert(test==0);
      execlp("./g","./g",NULL);
      exit(0);
    }
    wait(0);
    a--;
  }
  //a
  test = close(fds[0]);assert(test==0);
  test = close(fds[1]);assert(test==0);
  wait(0);
  system("ps -o pid,ppid,comm");
  return 0;
}
