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






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

    //int pid=getpid();
    pid_t pid;
    int antal = atoi(argv[1]);
    int fds1[2], fds2[2];
    if(pipe(fds1)<0 || pipe(fds2)<0)
        perror("Coouldn't pipe");

    int i;
    int result;
    int endResult;
    //printf("antal blev: %d", antal);


    pid = fork();

    if(pid==0){  ///b

        int result, a;
        close(fds1[1]);
        dup2(fds1[0], STDIN_FILENO);
        read(fds1[0], &result, sizeof(int));
        close(fds1[0]);
        close(fds2[0]);
        write(fds2[1], &result, sizeof(int));
        close(fds2[1]);
        exit(0);
    }


   for(i=0; i<antal; i++){  ///g
        pid=fork();
        if(pid==0){
            execlp("./g", "./g", NULL);
            exit(0);
        }
    }


    close(fds1[0]);
    close(fds1[1]);
    close(fds2[1]);
    wait(0);

    read(fds2[0], &result, sizeof(int));
    close(fds2[0]);
    printf("resultatet ar: %d \n", result);



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


}
