5
Hello. I need to create a process tree, until the moment what I was able to do was create a side of the tree, kill everything and then create the other side.
But I need to raise the whole tree first and start killing the children and the father.
My code that creates a side -> kills everything -> creates the other -> kills everything -> kills the father. I’ve tried using wait()
, waitpid()
and I can’t 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 I need to do:
what your difficulty?
– pmargreff
@pmargreff I can’t create both sides at once. I can only create one side -> this side dies -> only then create the other side. I need to create all the processes and only then kill them.
– PlayHardGoPro