mrigendra
mrigendra

Reputation: 1556

Fork call working

can anybody explain me working of fork in detail

#include<unistd.h>
#include<stdio.h>
int main ()
{
  int i, b;
  for (i = 0; i < 2; i++) {
    fflush (stdout);
    b = fork ();
    if (b == -1) {
      perror ("error forking");
    }
    else if (b > 0)             //parent process
    {
      wait ();
      printf ("\nparent %d", getpid ());
    }
    else
      printf ("\nchild %d %d", getpid (), getppid ());
  }
  return 0;
}

its just i need to know that if fork have same code as parent then this for loop should never stop creating child processes (every child will have its own for loop)

Upvotes: 1

Views: 89

Answers (3)

Trilok M
Trilok M

Reputation: 729

Yes although the parent and child code are the same but in parent the fork returns the child process id hence in parents code, the variable b contains the child's pid whereas the in child, the fork returns 0, hence in the child code segment the variable b will have 0 and so does we can achieve different jobs even though forking will have same parent code in child.

Upvotes: 0

Michael Laffargue
Michael Laffargue

Reputation: 10294

When you fork, the child process will continue with the same next instruction as the parent one and the values.

So it will stop one day ;)

Take a look at a similar question : fork in a for loop

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

Yes, each child will continue the loop, but the operative word here is "continue". The variable i will be inherited by the first child, and then increased, and this increased value is inherited by the second child, etc.

The same will happen in the children, as i is inherited and keeps it value from the parent process. This means that the loops will soon end in all children.

Upvotes: 2

Related Questions