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


#define READ 0
#define WRITE 1

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

    int status, test;
    int p1[2];
    int pid;
    int antalBarn;
    int i;
    antalBarn = atof(argv[1]);


    if(pipe(p1) == -1){
        perror("pipe failed!\n");
    }

    if(!fork()){ //barnet b ska läsa g,s pid

        int gPid;
        int sumIds = 0;

        test = close(READ); assert(test == 0);
        test = dup(p1[READ]); assert(test == READ);

        test = close(p1[READ]); assert(test == 0);
        test = close(p1[WRITE]); assert(test == 0);


        //läs piddana som g skickar!
        for(i = 0; i < antalBarn; i++){

            read(0, &gPid, sizeof(int));
            sumIds += gPid;

        }
        printf("Sum of pids: %d\n", sumIds);
        sleep(3);
        exit(0);
    }
    //a
    system("ps -o pid,ppid,pgid,sess,comm"); //X1
    printf("\n");

    //här skapas alla g processer
    for(i = 0; i < antalBarn; i++){

        pid = fork();
        if(pid == 0){ //g nummer i

            test = close(WRITE); assert(test == 0);
            test = dup(p1[WRITE]); assert(test == WRITE);

            test = close(p1[WRITE]);
            test = close(p1[READ]);

            sleep(3);
            //kör exec
            execlp("./g", "./g", NULL);
            perror("exec failed!");
            exit(1);

        }

    }
    //a
    test = close(p1[READ]); assert(test == 0);
    test = close(p1[WRITE]); assert(test == 0);

    system("ps -o pid,ppid,pgid,sess,comm"); //X2
    for(i = 0;i < antalBarn; i++)
        wait(&status);


    printf("\n");
    wait(&status); //vänta på b

    sleep(1);
    system("ps -o pid,ppid,pgid,sess,comm"); //X3


}
