Amine Amine - 1 year ago 67
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())
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 Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download