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

main()
{
    if(fork())
    {
        //printf("make process child to init\n ");
        exit(0); // kill parent
    }

    char str[10], *res;
    int x;
    FILE *fd=fopen("/home/me/Desktop/pipe","r");
    if(fd==NULL) exit(1);

    while(1)
    {
        res=fgets(str,10,fd);
        if(res!=NULL)
        {
            x=atoi(str);
            if(x==0) // echo "0">pipe stops daemon.
            {
                printf("Stopping daemon.\n");
                exit(0);
            }
            int tmpX=x;
            printf("putting %d children under init\n", x);
            if(!fork())
            {
                //extra parent

                for(x ; x>0 ; x--)
                {
                    if(!fork())
                    {
                        //child
                        sleep(15);
                        exit(0);
                    }
                }
                exit(0);
            }
            wait(0);
            system("ps -e -o pid,ppid,comm | grep uppg1"); //parent gets printed wonky but children get printed in a straight line
            x=tmpX;
            for(x ; x>0 ; x--)
            {
                wait(0);
            }
        }
        sleep(1);
    }

}
