Process Tree:

I want to make a process tree like the picture above. I wrote below code but if you look the PIDs, you'll find there's a problem!
My code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int a ;
int b ;
int c ;
int d ;
int e ;
int f ;
int g ;
int h ;
int i ;
b=fork();
if (b == 0) //it's child
{
d= fork();
if(d==0)
{
h=fork();
if(h==0)
{
i=fork();
if(i==0)
printf("%d: I\n", getpid());
else
printf("%d: H\n", getpid());
}
else
printf("%d: D\n", getpid());
}
else
{
e=fork();
if(e==0)
printf("%d: E\n", getpid());
else
{
f=fork();
if(f==0)
printf("%d: F\n", getpid());
else
printf("%d: B\n", getpid());
}
}
}
else
{
c=fork();
if(c==0){
g=fork();
if(g==0)
printf("%d: G\n", getpid());
else
printf("%d: C\n", getpid());
}
else
printf("%d: A\n", getpid());
}
return 0;
}
Output (UNIX):
10201: A
10203: C
10202: B
10204: G
10207: F
10206: E
10205: D
10208: H
10209: I
You can see G(pid)= 04 and it means it's made sooner than D(pid)= 05
There is an order which I would to create:
10201: A
10203: C
10202: B
10204: D
10207: G
10206: F
10205: E
10208: H
10209: I
This is my code for the above tree -
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(){
pid_t pid1, pid2, pid3, pid4,pid5,pid6,pid7,pid8,pid9,pid10,pid11;
printf("Parent of all: %d\n",getpid());
pid1 = fork();
if(pid1 == 0)
{ // A child Process. Lets say B.
printf("Child with id: %d and its Parent id: %d \n", getpid(),getppid());
pid2 = fork();
if(pid2 == 0){ // A child process. Lets say D.
printf("Child with id: %d and its Parent id: %d \n", getpid(),getppid());
}
else{
// A child process. Lets say E.
pid4 = fork();
if(pid4 == 0){
printf("Child with id: %d and its Parent id: %d \n", getpid(),getppid());
// A child process. Lets say H.
pid6=fork();
if(pid6 == 0)
{
printf("Child with id: %d and its Parent id: %d \n", getpid(),getppid());
// A child process. Lets say I.
pid7=fork();
if(pid7==0)
{
printf("Child with id: %d and its Parent id: %d \n", getpid(),getppid());
}
}
}
else{
pid5=fork();
if(pid5 == 0)
{ // A child process. Lets say F.
printf("Child with id: %d and its Parent id: %d \n", getpid(),getppid());
}
}
}
}
if(pid1 > 0){
pid3 = fork();
if(pid3 == 0){ // A child process. Lets say C.
printf("Child with id: %d and its Parent id: %d \n", getpid(),getppid());
// A child process. Lets say G.
pid10=fork();
if(pid10 == 0)
{
printf("Child with id: %d and its Parent id: %d \n", getpid(),getppid());
}
}
}
for(int i=0; i<3; i++)
wait(NULL);
}
Output is -

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With