#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
int main (int argc, char **argv){
    int n, i,x=0;
    n = atoi (argv[1]);
    int pid,test;
    int fds1[2];
    pipe(fds1);

    pid = fork();
    switch(pid){
    case -1:
        printf("Fork failed exeting\n");
        exit(0);
    case 0:// process b
        //redirect pipe
        test = close(0); assert(test==0);
        test = dup(fds1[0]); assert(test==0);
        //close all loose ends
        test = close(fds1[0]); assert(test==0);
        test = close(fds1[1]); assert(test==0);

        for(i=0; i<n; i++){
            read(0,&pid,sizeof(int));
            x+=pid;
        }
        printf("Sum of pids = %d",x);
        sleep(1);
        exit(0);

    default://a
        for(i=0; i<n; i++){
            pid = fork();
            switch(pid){
            case -1:
                printf("Fork failed exeting\n");
                exit(0);
            case 0:// process g
                //redirect pipe
                test = close(1); assert(test==0);
                test = dup(fds1[1]); assert(test==1);
                //close all loose ends
                test = close(fds1[0]); assert(test==0);
                test = close(fds1[1]); assert(test==0);

                //exec to g
                execlp("./g","./g",NULL);
                printf("Exec failed exit\n");
                exit(0);

            default:
                system("ps -o pid,ppid,comm");
                wait(0);
            }
        }
        // a waiting for b
        wait(0);
        system("ps -o pid,ppid,comm");
    }

    return 0;

return 0;
}

