#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/types.h>
#define WRITE 1
#define READ 0

int main (int argc, char* argv[])
{
    int fds[2]; int i;
    int test;
    pipe(fds);
    int x;
    int sum =0;
    int a=atoi(argv[1]);

    if(!fork())
    {
        for(i = 0; i<a;i++)
        {
        read(fds[READ],&x,sizeof(int));
        sum += x;
        }
        close(fds[READ]);
        close(fds[WRITE]);
        printf("Sum:%d\n", sum);
        sleep(5);
        exit(0);
    }
    system("ps -o pid,ppid,comm");

    sleep(1);
    for(i=0;i<a;i++)
    {
        if(!fork())
        {
            system("ps -o pid,ppid,comm");
            close(WRITE);
            dup(fds[WRITE]);
            close(fds[READ]);
            close(fds[WRITE]);
            execlp("./g", "./g", NULL);
            exit(0);
        }

        wait(0);
    }

    sleep(5);
    close(fds[READ]);
    close(fds[WRITE]);
    wait(0);
    system("ps -o pid,ppid,comm");


}
