Search code examples
cfork

How can I create a child child?


How can I create a child's child's child? How can I do this 10 times. In the code below, the parent is fixed and the children are formed. How can I ensure that the child I want to have a child? enter image description here

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() 
{ 
    for(int i=0;i<5;i++) // loop will run n times (n=5) 
    { 
        if(fork() == 0) 
        { 
            printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid()); 
            exit(0); 
        }else{
        printf("parrent");
        }
    } 
    for(int i=0;i<5;i++) // loop will run n times (n=5) 
    wait(NULL); 

}

Solution

  • The following should serve as a basic example of what you're attempting to do:

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    
    int nSubprocess_count = 0;
    int nFork_result;
    
    int main() 
      { 
      nFork_result = fork();
      while(nFork_result == 0)
        {
        printf("child %d from parent %d\n", getpid(), getppid()); 
    
        nSubprocess_count += 1;
    
        if(nSubprocess_count < 10)
          nFork_result = fork();
        else
          break;
        }
    
      if(nFork_result != 0)
        printf("parent %d\n", getpid());
    
      sleep(5);
      }
    

    When run this produces output similar to:

    parent 4522
    child 4523 from parent 4522
    parent 4523
    child 4524 from parent 4523
    parent 4524
    child 4525 from parent 4524
    parent 4525
    child 4526 from parent 4525
    parent 4526
    child 4527 from parent 4526
    parent 4527
    child 4528 from parent 4527
    parent 4528
    child 4529 from parent 4528
    parent 4529
    child 4530 from parent 4529
    parent 4530
    child 4531 from parent 4530
    parent 4531
    child 4532 from parent 4531
    

    As you can see, each child process forks one additional child process.

    OnlineGDB here