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

main(){
    char str[10], *res;
    int x;
    int i, pid;
    FILE *fd;

    pid = fork();
    switch(pid)    {
    case -1:
        printf("fork failed exeting\n");
        exit(0);
    case 0: //deamon
        fd=fopen("/home/me/Desktop/pipe","r");
        while(1)
        {
            res=fgets(str,10,fd);
            if(res!=NULL){
                x=atoi(str);

                if(x>0){
                    printf("adding %d child(ren) under init.\n", x);
                    for(i=0; i<x ;i++){
                        pid = fork();

                        switch(pid){
                        case -1:
                            printf("fork failed exeting\n");
                            exit(0);
                        case 0://child to create child under init
                            pid = fork();
                            switch(pid){
                            case -1:
                                printf("fork failed exeting\n");
                                exit(0);
                            case 0:
                                sleep(15);
                                exit(0);
                            default://exit to create child under init
                                exit(0);
                            }
                        default:
                            wait(0);
                        }
                    }

                    system("ps -e -o pid,ppid,comm | grep uppg1");
                }
                else{
                    printf("Stopping deamon.\n");
                    exit(0);
                }

            }
            sleep(1);
        }
    default:// creating deamon
        printf("creating deamon\n");
        exit(0);
    }


}
