Here is a code that creates two childern using fork. My question is how can we create mutiple grandchildern and great grandchildern at the same time . And the line 21 of code gives an unexpected output i.e instead on one parent id it gives three id's.

Here is the output :-
This is a child1 process and pid is 3271
This is child2 process and pid is 3272
The parent process has pid 2206
The parent process has pid 3270
The parent process has pid 1.

#include<stdio.h>
main()
{
  int child1,child2;
  int i;
  child1 = fork();
  if(child1==0)
  {
    printf("This is a child1 process and pid is %d\n", getpid());
  }
   else
    {
          child2=fork();     
      if(child2==0)
        {
              printf("This is child2  process and pid is %d\n",getpid());
        }
      }
    sleep(1);
       printf("The parent process has pid %d\n",getppid());


}

Look at the scoping of your statements. Each process will output info about the parent process, including the root process, hence the 3 messages about parent process pids. This is where properly indenting your blocks of code can be helpful. IE:

#include <stdio.h>
int main(void)
{
    int child1,child2;
    int i;
    child1 = fork();
    if(child1==0)
    {
        printf("This is a child1 process and pid is %d\n", getpid());
    }
    else
    {
        child2=fork();     
        if(child2==0)
        {
            printf("This is child2  process and pid is %d\n",getpid());
        }
    }
    sleep(1);
    printf("The parent process has pid %d\n",getppid());
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.