Amine Amine - 14 days ago 5
C Question

Can someone help me understand how fork worked in this case?

I have this program that I find somewhat misleading and hard to understand:

int i=2;
int j=10;
int p;

while(--i && (p=fork())
{
if(p<0)
exit(EXIT_SUCCESS);
}
j=j+2;
if(p==0)
{
i=i*3;
j=j*3;
}
else
{
i=i*3;
j=j*2;
}
printf("pid=%d i=%d j=%d\n",getpid(),i,j);


This program results the following:


Parent: PIDHERE, i=0, j=24.

Child: PIDHERE, i=3, j=36.


But why does this exactly happen? If parent has i=0 it means the while was executed twice, but doesn't that mean two childs are created instead of one since the while has a fork() statement?

Also, when does the while exactly stop looping? (the logical expression is confusing with the fork()!).

pat pat
Answer

The --i predecrements i. The first time the while evaluates its condition, it will see i has a value of 1. The second time, it will see i has a value of 0. So, the loop will only spawn one child.

The while stops when it sees i is 0 (in the parent), or if the fork returns 0 (in a child).