Processes in Unix

I am trying to play and create processes and found this piece of code....

int myMain(int argc , char* argv[]){
 
  childID = 0;
for (j=1;j<3;j++)
   if (childID = fork())
       break;

fprintf(stderr, " process ID:%d  parent ID:%d  child ID:%d\n",  getpid(), getppid(), childID);

 return 0;
}

I am confused by following. Main process will get to for loop and create first child. Then it will continue and print (fprint process id,child id parent id). When it is done with that should that main process go back up at the beginning of the loop. while at same time child that was created will print and go back up to the beginning of the loop.Am i looking at this right way?

The parent process will break out of the loop at the if() because its return value will be zero. So it should be

  • parent creates child and quits
  • child prints, forks again, and quits
  • child's child prints, forks again, and quits

Which you're right, is odd. It's backwards I think. if(! (childID = fork()) ) break; , and putting the if after the print, would make every process print and only the parent process fork.

Hi again:)....thanks for reply..
You said parent would break out of loop because it child value be zero.
When parent forks shouldn't his child value be value of child just forked. Child just created will have child id =zero?

---------- Post updated at 06:35 PM ---------- Previous update was at 06:19 PM ----------

Lets say first time process fork.....at that point its child id is not zero......child that parent created has child Id =0.

You're right, I had it backwards. Don't know how I managed that while referring to the manpage!