I'm doing a program with the objective of creating a process within a process 3 times(get a child process(1), a grand child process(2) and a grand grand child(3) process) and do actions in each process in reverse order of the creation order. Which means first I do the actions of (3) then the actions of (2) then of (1) then of the parent process. But the output is weird like doing 6 printfs and multiple processes saying they have the same pid.
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
pid_t mypid = getpid();
pid_t child1_pid=fork();
pid_t child2_pid=-1; //waiting for child1 to fork
pid_t child3_pid=-1; //waiting for child2 to fork
int status;
if(child1_pid==0)
{
mypid=getpid();
child2_pid=fork()
if(child2_pid==0)
{
mypid=getpid();
child3_pid=fork()
if(child3_pid==0)
{
mypid=getpid();
printf("3: Im %ld and my parent is %ld\n", mypid, getppid());
}
wait(&status);
printf("2:Im %ld and my parent is %ld\n", mypid, getppid());
}
wait(&status);
printf("1:Im %ld and my parent is %ld\n", mypid, getppid());
}
else
{
wait(&status);
printf("\nIm the father and my pid is %ld\n", mypid);
}
return 0;
}
What I'm asking is what I'm doing wrong and where is my logic incorrect and maybe point me to some reading in the web. Thanks in advance.