Search code examples
c++cforksystems-programming

How to create one level process tree using fork() system call?


I want to create a one level process tree using fork() system call, which looks as follows for n = 4 process

enter image description here

I have tried this with the following code but this is not working. (here 1 is a child of parent process )

    for(i = 0 ;i < n; i++){
    chid = fork();
    if ( chid == 0 ){
        printf("%d\n",getpid());
        while(++i < n){
            chid = fork();
            if(chid == 0){
                printf(" %d ",getpid());
                break;
            }
        }
    }
    else
        break;
} 

How can I make this ?


Solution

  • #include<stdio.h>
    
    int main()
    {
      int i;
      pid_t  pid;
    
      for(i=0; i<5; i++)
      {
        pid = fork();
        if(pid == 0)
          break;
      }
      printf("pid %d ppid %d\n", getpid(), getppid());
      if(pid == 0)
      {
        /* child process */
      }
    }
    

    Based on the discussion, here is the modified program.

    #include<stdio.h>
    #include<unistd.h>
    
    int main()
    {
      int i;
      pid_t  pidparent, pid;
    
      if( (pidparent = fork()) == 0 )
      {
        for(i=0; i<3; i++)
        {
          pid = fork();
          if(pid == 0)
            break;
        }
        if(pid == 0)
        {
          printf("child %d parent %d\n", getpid(), getppid());
        }
      }
      else
      {
        printf("parent %d \n", pidparent);
      }
      /* printf("pid %d ppid %d\n", getpid(), getppid()); */
    }