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



int main(int argc, char* argv[])
{
    pid_t pid;
    int fds[2],number,i,pidsum=0,test;
    if(pipe(fds)==-1)
    {
        fprintf(stderr,"Pipe did not work\n");
    }

    number=atoi(argv[1]);

    pid=fork();
    if(pid==-1)
    {
        fprintf(stderr,"Fork did not work\n");
        exit(1);
    }

    else if(pid==0)
    {
        test=close(fds[1]); assert(test==0);
        while(read(fds[0],&pidsum,sizeof(int)))
        {
            pid=pid+pidsum;

        }
        printf("total is: %d\n",pid);
        exit(0);
    }

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

    test=close(fds[0]); assert(test==0);
    for(i=0;i<number;i++)
    {

        pid=fork();
        if(pid==-1)
        {
            fprintf(stderr,"Fork did not work\n");
            exit(1);
        }
        else if(pid==0)
        {
            test=close(1); assert(test==0);
            test=dup(fds[1]); assert(test==1);
            test=close(fds[1]); assert(test==0);
            execlp("./g","./g",NULL);
            printf("exec fail\n");
            exit(1);
        }
        sleep(1);
        system("ps -o pid,ppid,comm");
        wait(0);
    }
    test=close(fds[1]); assert(test==0);



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


    return 0;
}
