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

int childLeft;

int main(int argc, char * argv[])
{
	int nProc, i, sumPids, a;
	nProc = atoi(argv[1]);
	childLeft = nProc;

	pid_t pidb, pidg;
	pidb = fork();
	i = 0; sumPids = 0; a = 0;

	int fds1[2];
	pipe(fds1);
	int test;
	int testVar;

	
	switch(pidb)
	{
		case -1:
			fprintf(stderr, "error!");
			exit(0);
		case 0:
			//childproc
			system("ps -o pid,ppid,comm");
			dup(fds1[0]);
			close(fds1[1]);
			while (childLeft > 0)
			{
				read(fds1[0],&a,sizeof(int));
			
				childLeft --;
				sumPids += a;
				
			}

			exit(0);
		default:
			//parent
			sleep(1);
			for (i; i< nProc; i++)
			{
				pidg = fork();
				switch(pidg)
				{
					case -1:
						fprintf(stderr, "error!");
						exit(0);
					case 0:
						sleep(2);
						dup2(fds1[1], 1);
						close(fds1[0]);

						system("ps -o pid,ppid,comm");
						execlp("./g", "./g", NULL);
    						fprintf(stderr,"execlp did not work\n");
      						exit(1);
						//childproc
					default:
						//parentproc
						wait(0);
				}
			}
			wait(0);
			printf("Sum pids: %d\n", sumPids);
	}

	return 0;
}
