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

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

    pid=fork();
    if(pid>0)
    {
        exit(0);
    }
    else
    {
        while(1)
        {
            res=fgets(str,10,fd);
            if(res!=NULL)
            {
                x=atoi(str);
                printf("x: %d.\n", x);
                if(x<=0)
                {
                    printf("stopping daemon\n");
                    exit(0);
                }
                else
                {
                    printf("Adding %d children under init\n",x);
                    pid=fork();
                    if(!pid)
                    {
                        for(i=0; i<x; i++)
                        {
                            if(!fork())
                            {
                                sleep(15);
                                exit(0);
                            }



                        }
                        exit(0);

                    }

                    wait(0);

                }
                system("ps -e -o pid,ppid,comm | grep uppg1");
            }
            sleep(1);
        }
    }

}
