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

int main(int argc, char *argv[])
{
    int d = atoi(argv[1]);
    int p1[2];
    pipe(p1);

    if(!fork())
    {
        int pid;
        int sumpid = 0;
        //BARN B
        close(p1[1]);
        while(read(p1[0],&pid,sizeof(int)))
        {
            sumpid = sumpid + pid;
        }
        printf("Summan av pid : %d\n", sumpid);
        close(p1[0]);
        exit(0);
    }
    system("ps -o pid,ppid,comm");
    int i;
    for(i=0; i<d; i++)
    {
        if(!fork())
        {
            //BARN G
            close(1);
            dup(p1[1]);
            close(p1[1]);
            close(p1[0]);
            execlp("./g","./g",NULL);
        }

        system("ps -o pid,ppid,comm");
        close(p1[0]);
        wait(0);
    }
    close(p1[1]);
    wait(0);
    system("ps -o pid,ppid,comm");
}
