clinuxfork

Calculating total number of processes in fork() code


I am trying to determine how many processes are generated in the following code:

#include <stdio.h>
#include <unistd.h>

int main() {  

    int i = 1;

    if (fork()) //parent process will return PID of child.
        i++;
    else if (fork()) //child process (becomes parent)
        i--;
    else //grandchild process returns 0
        i++;

    printf("%d\n", i);
}

Generally, the formula for total # of processes is 2^n where n is the number of fork system calls. I am confused because this sample involves if/else conditional statements.

I am getting 4 processes in total. (2 processes from the if (fork()) statement and 2 processes from the else if (fork()) statement). Can someone confirm if this is correct or not? And if not, can you please guide me in the right direction / explain how to calculate the number of processes. This is something I'm having quite a bit of trouble determining.


Solution

  • Pay attention: the if () statements will be evaluated true even if the fork() does not succed since in this case it returns a negative number which is different from 0 and so true.

    You have 3 processes

    The first fork() generate a copy of the parent process, i.e, a child. Now you have 2 processes. The fork() returns the child PID to the parent. This makes the first if() condition true for the parent, and false for the children. The parent increments the variable i.

    So, the child flow goes into the second if statement which executes a fork before being evalated. The fork generates a copy of the child (which now became the parent), i.e, a grandchild. You now have 3 processes.

    The child evaluates the else if condition true and will decrement the i while the grandchild evaluates false and will increment i.

    As a matter of what I say, if you try to exectute your program, you'll get only 3 outputs (3 printf() executed). The order of the output depends on how the processes are scheduled by the CPU scheduler and it's something you cannot predict.