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

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

	int fds1[2];
	int test, a,pid,i,sum=0,antal;
 	pipe(fds1);
 	antal=atoi(argv[1]);

	pid=fork();
	if(!pid){
        test = close(fds1[1]); assert(test==0);
        while(read(fds1[0],&a,sizeof(int))){
            sum=sum+a;
        }
        printf("Sum of pids: %d.\n", sum);
		sleep(antal*2);
		test = close(fds1[0]); assert(test==0);
		exit(0);



	}
    system("ps -o pid,ppid,comm");
    printf("\n");
	for(i=0;i<antal;i++){
        if(!fork()){
            sleep(2);
            test = close(1); assert(test==0);
            test = dup(fds1[1]); assert(test==1);
            test = close(fds1[0]); assert(test==0);
            test = close(fds1[1]); assert(test==0);
            execlp("./g", "./g", NULL);
            sleep(2);
            exit(0);

        }else

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

            sleep(2);

            wait(0);
	}
	if(pid>0){
    test = close(fds1[1]); assert(test==0);

	wait(0);
    test = close(fds1[0]); assert(test==0);

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