Hello. I need to create a process tree, so far what I managed to do was create one side of the tree, kill everything and then create the other side. But I need to create the whole tree before and start killing the children and the father.
My code that creates a side - > kills everything - > creates the other - > kills everything - > kill dad I've already tried to use wait()
, waitpid()
and I can not get P4 to wait for P5 and both wait for P6 and P7
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>
int main(){
clock_t t;
double time_taken;
t = clock();
int status;
pid_t idProcesso; // P1
printf("I'm P1: %d | my dad: %d\n", getpid(), getppid());
idProcesso = fork();
switch(idProcesso){
case -1: exit(-1); //ERROR
case 0: //P2
printf("I'm P2: %d | my dad P1: %d\n", getpid(), getppid());
idProcesso = fork();
switch(idProcesso){
case -1: exit(-1); //Error
case 0: //P4
printf("I'm P4: %d | my dad P2: %d\n", getpid(), getppid());
break;
default: //Continue P2
wait(&status);
printf("I'm P2: %d | Already waited for my son P4: %d\n", getpid(), idProcesso);
idProcesso = fork(); //P5
switch(idProcesso){
case -1: exit(-1); //ERROR
case 0: //P5
printf("I'm P5: %d | my dad P2: %d\n", getpid(), getppid());
break;
default: //Continue P5
wait(&status); //P2 waits his son P5
printf("I'm P2: %d | Already waited for my son P5: %d\n", getpid(), idProcesso);
break;
}
}
break;
default: //Continue P1
wait(&status);
printf("I'm P1: %d | Already waited for my son P2: %d\n", getpid(), idProcesso);
idProcesso = fork(); //P1 creates son
switch(idProcesso){
case -1: exit(-1); //ERROR
case 0://P3
printf("I'm P3: %d | my dad P1: %d\n", getpid(), getppid());
idProcesso = fork(); //P3 creates son P6
switch(idProcesso){
case -1: exit(-1); //ERROR
case 0: //P6 son of P3
printf("I'm P6: %d | my dad P3: %d\n", getpid(), getppid());
break;
default: //Continue P3
wait(&status); //P3 waits his son P6
printf("I'm P3: %d | Already waited for my son P6: %d\n", getpid(), idProcesso);
idProcesso = fork(); //P3 creates son P7
switch(idProcesso){
case -1: exit(-1);//ERROR
case 0: //P7 son of P3
printf("I'm P7: %d | son of P3: %d\n", getpid(), getppid());
break;
default: //P3 waits son P7
wait(&status);
printf("I'm P3: %d | Already waited for my son P7: %d\n", getpid(), idProcesso);
break;
}
break;
}
break;
default: //Continue P1
wait(&status); // P1 waits his son P3
printf("I'm P1 again, my id: %d\n", getpid());
t = clock() - t;
time_taken = ( (double)t ) / CLOCKS_PER_SEC;
printf("Time used in seconds: %f\n", time_taken);
}
break;
} //SWITCH
} //Main
What do I need to do: