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

// H

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

  while(1) {
    res=fgets(str,10,fd);
    if(res!=NULL) {
        x=atoi(str); printf("x: %d.\n", x);
        system("ps -e -o pid,ppid,comm | grep uppg1");
        if(x == 0)
        {
            // Stopping daemon;
            printf("Stoping daemon.\n");
            break;
        }
        else if(x < 0)
        {
            // Wrong input
            printf("Wrong input, must be 1 or higher, exiting.\n");
            break;
        }
        else
        {
            printf("Adding %d children under init.\n", x);
            for(i = 0; i < x; i++)
            {
                if(!fork())
                {
                    // parent
                    if(!fork())
                    {
                        // child
                        sleep(15);
                        exit(0);
                    }
                    exit(1);
                }
                wait(0);
            }
        }
        system("ps -e -o pid,ppid,comm | grep uppg1");
    }
    sleep(1);
  }

}
