A while loop will run until the condition in the parentheses is false. In this case that would be: until the return value from fork() is not equal to 0.
fork()'s return is:
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.
So once fork executes successfully there are 2 processes (the parent and one new child). One of them will return 0 (the child process), the other (the parent process) will return some other value (the PID of the child).
So this tells you that the code runs forever as each child process will continue to execute the while() loop.
Say your parent is PID=0†, first child is PID=1†, etc. The first run of the code would be something like:
while(fork()==0) // now there are two processes, the child which returns 0 and the { // parent which returns 1 (the new child's pid) if(fork() == 0) break; // this code is now only executed by the child (1) as the // parent already left the while loop since it's return was // not == 0 // once this code executes there are 2 processes running // child(1) will return child(2)'s PID, child(2) will // return 0 and will enter the if and break from the loop // now here it's only the original child(1) running again }
So you'll end up with something like:
0 is the original parent, it makes a child and leaves 1 is the original child, it creates a child(2) and then goes to the while loop again where it generates 3 before leaving 2 is the child of 1 where it leaves because of the break in the if 3 now hits the if and generates 4 (which leaves because of the break) 3 now goes back to while and generates 5 then leaves, etc etc +--> 4 | | (if) | 0 --> 1 -+--> 3 ---> 5 | |(if) | +--> 2
† - These are not realistic PIDs to get while running your user space code on any modern Linux distro, however they're easier to read then a real random string so I'm using them.