0

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 ?

Lakshya Garg
  • 736
  • 2
  • 8
  • 23

1 Answers1

1
#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()); */
}
Umamahesh P
  • 1,224
  • 10
  • 14
  • Also worth noting that inside the `/* child process */` block `i+2` is the same as the label in the original diagram (2,3,4) – Michael Anderson Mar 04 '16 at 02:50
  • @Michael in question, 1 is also a child process of parent process. – Lakshya Garg Mar 04 '16 at 03:16
  • Ah, I'd assumed that 1 was the parent process. (And it looks like the author of this answer assumed this too.). I guess that means you just wrap the `for` loop with a `if((pid=fork())==0) { ... }` – Michael Anderson Mar 04 '16 at 03:21
  • Yeah, I guess I got the answer with this. If a create a child process and use this loop inside that process for the rest of the children it will work fine. – Lakshya Garg Mar 04 '16 at 03:28
  • I have added the modified program. Please feel free to comment if there is any issue. – Umamahesh P Mar 04 '16 at 03:39