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

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

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

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

	
	switch(pidb)
	{
		case -1:
			fprintf(stderr, "error!");
			exit(0);
		case 0:
			//childproc
			system("ps -o pid,ppid,comm");
  			while (childLeft > 1)
			{
				read(fds1[0],&a,sizeof(int));
				
					printf("A som streng: %s \n\n A som int: %d \n\n", a, a);
					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:
						test = close(0); assert(test==0);
      						test = dup(fds1[0]); assert(test==0);
						test = close(fds1[0]); assert(test==0);
						test = close(fds1[1]); assert(test==0);
						test = close(1); assert(test==0);
						test = dup(fds2[1]); assert(test==1);
						test = close(fds2[1]); assert(test==0);
						test = close(fds2[0]); assert(test==0);
						sleep(1);
						childLeft --;
						
						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;
}
