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

#define READ 0
#define WRITE 1

int main(int argc, char* argv[])
{
    int gUnit=atoi(argv[1]), gUnitTmp=gUnit, fds1[2],fds2[2],test,pidBuf, pidSum=0;
    printf("%d g-processes will be made and pids summed.\n", gUnit);

    pipe(fds1);
    if(!fork())
    {
        //B
        printf("Hello, i sum pids and my pid is %d\n",getpid());
        for(gUnit; gUnit>0; gUnit--)
        {
            read(fds1[READ], &pidBuf, sizeof(int));
            pidSum+=pidBuf;
        }

        printf("\nsum of pids is: %d\n",pidSum);
        exit(0);
    }//B
    system("ps -o pid,ppid,comm"); //should be two processes, A and B

    for(gUnit ; gUnit>0 ; gUnit--)//loop for making g-processess
    {
        if(!fork())
        {
            printf("hello am g-process with pid %d\n",getpid());
            system("ps -o pid,ppid,comm"); //prints A,B and a G process
            test=close(WRITE); assert(test==0);
            test=dup(fds1[WRITE]); assert(test==WRITE);
            test=close(fds1[WRITE]); assert(test==0);
            test=close(fds1[READ]); assert(test==0);
            sleep(4);
            execlp("./g","./g",NULL);
            perror("Shouldn't go here.\n");
        }

        wait(0);
    }

    gUnit=gUnitTmp;



    wait(0);//wait for B
    test=close(fds1[WRITE]); assert(test==0);
    test=close(fds1[READ]); assert(test==0);
    system("ps -o pid,ppid,comm"); //Lone A process
    return 0;
}
