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

int main(int argc, char* argv[])
{
    int nrOfGs = atoi(argv[1]);
    printf("G processes: %d\n",nrOfGs);
    int bPid, pipeMsg, i, gPid, readSum = 0;
    int sumPipe[2];
    if(pipe(sumPipe)){
        printf("Error when creating pipe\n");
        exit(1);
    }
    int pidPipe[2];
    if(pipe(pidPipe)){
        printf("Error when creating pipe\n");
        exit(1);
    }
    switch(bPid = fork()){
        case -1:
            printf("Error when forking\n");
            exit(1);

       case 0:
            //This is b process
            close(0);
            dup(pidPipe[0]);
            close(1);
            dup(sumPipe[1]);
            int nrOfRead = 0;
            int sum = 0;
            while(nrOfRead < nrOfGs && read(0, &pipeMsg, sizeof(int))){
                sum += pipeMsg;
                nrOfRead++;
            }
            write(1, &sum, sizeof(int));
            exit(0);
        default:
            close(sumPipe[1]);

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

    for(i = 0; i < nrOfGs; i++){
        switch(gPid = fork()){
            case -1:
                printf("Error when forking G\n");
                exit(1);
            case 0:
                //This is g process
                close(1);
                dup(pidPipe[1]);
                //when using exec, the process worked as expected but did not show up on the specified system("ps -o pid,ppid,comm"); command
                //execl("/home/vten1359/H/g.out", "g", NULL);
                int pid=getpid();
                sleep(1);
                write(1,&pid,sizeof(int));
                exit(0);
            default:
                system("ps -o pid,ppid,comm");
                wait(0);

        }
    }
    close(pidPipe[0]);
    close(pidPipe[1]);

    wait();
    read(sumPipe[0], &readSum, sizeof(int));
    printf("\nSum of pids: %d\n",readSum);
    system("ps -o pid,ppid,comm");



  return 0;

}
