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

int main(int argc, char *argv[])
{
	int n = atoi(argv[1]);
	int i;
	int gpid;
	int pidsum = 0;
	int p1[2];
	pipe(p1);
	
	if(!fork())//B
	{
		close(p1[1]);
		while(read(p1[0], &gpid,sizeof(int)))
		{
			pidsum += gpid;
			sleep(1);
		}
		close(p1[0]);
		printf("Sum of pids: %d\n",pidsum);
		exit(0);	

	}
	system("ps -o pid,ppid,comm");
	for(i = 0; i<n; i++)
	{
		if(!fork())//G
		{	
			system("ps -o pid,ppid,comm");
			close(1);
			dup(p1[1]);
			close(p1[0]);
			close(p1[1]);
			execlp("./g","./g",NULL);
		}
			wait(0);
		sleep(1);
	}
	close(p1[0]);
	close(p1[1]);
	wait(0);
	system("ps -o pid,ppid,comm");


}
