Here is how my program articulates: there is a parent that forks a child and this child forks itself another child. So There is a parent, a child and a subchild (i.e. the parent of this subchild is the child).
The child execute a command with execlp(), let's say date to make it simple. The subchild do the same.
Of course the child forks the subchild before executing the command.
I am looking for the subchild to execute the command AFTER the child executed its own command. Moreover after the child and subchild executed their command, I would like the parent to continue its own process.
I have 2 problems:
- I don't know how to make the parent to wait for the subchild execution
- I can't make the subchild wait for the child execution (does the child lose its pid when using execlp?)
Here is my current implementation:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (int argc, char **argv){
pid_t pid1, pid2;
pid1 = fork();
if (pid1 > 0)
{
int status;
// Wait child
printf("Parent waiting for child\n");
waitpid(pid1, &status, 0);
printf("Parent has waited child\n");
// Wait subchild
printf("Parent waiting for subchild\n");
// Wait sub-child here?
printf("Parent has waited subchild\n");
// End
printf("parent end\n");
}
else
{
pid2 = fork();
// Subchild
if (pid2 == 0) {
waitpid(getppid(), NULL, 0); // wait child? it doesn't work
execlp("/bin/date", "date", "+Subchild:\"%d-%m-%y\"", (char *) 0);
_exit(EXIT_FAILURE);
}
// Child
else {
execlp("/bin/date", "date", "+Child:\"%d-%m-%y\"", (char *) 0);
_exit(EXIT_FAILURE);
}
}
return 0;
}
My two "problems" are line 21 and 33.
The output is the following:
Parent waiting for child
Subchild:"03-10-17"
Child:"03-10-17"
Parent has waited child
Parent waiting for subchild
Parent has waited subchild
parent end
The subchild executes itself as fast as it can... I resolved this by using shared variable but it felt like a workaround and I still had issues with the parent waiting for the subchild.