0

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());


}
2
Contributors
1
Reply
15
Views
4 Years
Discussion Span
Last Post by rubberman
0

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;
}

Edited by rubberman

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.