Fork ()

hi all
About this code

for (i = 1; i < n; i++)
if ((childpid = fork()) <= 0)
break;

I really can't understand the output .

and the way fork () return the value .
how about the process Id ,the child process Id and the parent ID
in this case

so please answer me soon

fork() is a bit special, you call it once but return twice :smiley:
That is it returns once in the child with return code of 0, and return once in parent with retcode of the child pid, if all went right and if my memories didnt fail agen

I think there will be n process at the end. If u skip break statement then u will get 2^n process ( 2 to the power of n).

Regards,

If it all if there is any anything to be done by the child

there would be only 2^(n-1)-2 child processes
and 1 parent process
as for validates between and 1 and < n

People try to be a little too clever with fork sometimes... whenever I use it I try to write my code like this:

pid_t pid=fork();
if(pid > 0)
{
  int status;
  /* This process has created an independent child process */

  do_other_stuff();

  /* Wait for it to finish so it doesn't become a zombie */
  wait(&status);
}
if(pid == 0)
{
  /* This process IS the child process! */
  do_stuff();

  /* Exit the program when we're done doing stuff */
  exit(0);
}
else
{
  /* No child process was created because of some sort of error */
}

this could be a better way,

pid_t pid;
if( (pid=fork()) < 0 )
{
/* Error Stuff /
}
else if(pid == 0 )
{
/
child stuff /
}
else
{
/
parent stuff */
}

the above will not mandate two if-condition checks