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

int main(int argc, char const *argv[]){

    pid_t pid, mypid, childpid;
    int i, g = atoi(argv[1]), p[2], test, sum = 0;

    if(pipe(p) < 0){
        perror("PIPE ERROR!\n");
        exit(1);
    }

    switch(pid = fork()){

    case -1:
        perror("FORK ERROR!\n");
        exit(1);

    //Child B
    case 0:
        test = close(0); assert(test == 0);
        test = dup(p[0]); assert(test == 0);
        test = close(p[1]); assert(test == 0);
        while(read(p[0], &childpid, sizeof(pid_t))){
           sum = sum + childpid;
        }
        test = close(p[0]); assert(test == 0);
        //printf("B: %d\n", getpid());
        printf("Sum of pids: %d\n", sum);
        exit(0);

    default:
       system("ps -o pid,ppid,comm");
        for(i = 1; i <= g; i++){
            switch(pid = fork()){
                    case -1:
                    perror("FORK ERROR\n");
                    exit(1);

                    // Child G
                    case 0:
                        test = close(1); assert(test == 0);
                        test = dup(p[1]); assert(test == 1);
                        test = close(p[0]); assert(test == 0);
                        execlp("./g", "./g", NULL);

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

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

    return 0;
}
