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

createChilds(int numberChild)
{
	pid_t pid, pid2;
	int i = 0;

	for (i; i< numberChild; i++)
	{
		pid = fork();
		switch(pid)
		{
			case -1:
				fprintf(stderr, "Error");
				exit(0);
			case 0:
				//Child
				pid2 = fork();
				switch(pid2)
				{
					case -1:
						fprintf(stderr, "Error");
						exit(0);
					case 0:
						sleep(15);
						exit(0);
					default:
						exit(0);
				}
			default:
				//parent
				wait(0);
				break;
		}
	}
}

main()
{
	char str[10], *res; int x;
  	FILE *fd=fopen("/home/me/Desktop/pipe","r");
	pid_t pid;
	pid = fork();

	switch(pid)
	{
		case -1:
			fprintf(stderr, "error");
			exit(1);
		case 0:
			//Child
  			while(1) 
			{
    				res=fgets(str,10,fd);
				if(res!=NULL) 
				{	
					x=atoi(str);
					if (x > 0)
					{
						printf("Adding %d under init\n", x);
						createChilds(x);
					} else
					{	
						printf("Stopping deamon.\n");
						exit(0);
					}
					system("ps -e -o pid,ppid,comm | grep uppg1");
				}
		    	sleep(1);
		  	}
			exit(0);
		default:
			exit(0);
			//Parent	
	}
}
