I am stuck on the line of code pid = fork();
, I understand prior to that there are 2 child process created, but would some please clarify once it reaches to the line pid=fork();
, does the previous child being wiped and pid will start forking from 0 again or does it just keep forking with the 2 child ?
void main() {
int pid = fork();
if(pid != 0)
fork();
pid = fork();
if(pid == 0)
fork();
fork();
exit(0);
}
if fork() is successful it returns 0 to the child and the process id to the parent. So for the parent, pid != 0 and for the children it is. After the first if, before the
pid = fork()
line. There is 3 processes. These 3 processes then create one new child each, which then in turn creates another child.Finally all processes spawn one child. This gives us (3 + 3 + 3) * 2 = 18 processes if none of the fork() fails.