retagged by
412 views
4 votes
4 votes

Given the following piece of code

main(int argc, char ** argv)
{
    forkthem(5)
}
void forkthem(int n)
{
    if(n > 0)
    {
        fork();
        forkthem(n-1);
    }
}

How many processes are created if the above piece of code is run? (Hint: It may be easier to solve this problem by induction/recursion.)

retagged by

2 Answers

3 votes
3 votes

To solve this problem, we compute the number of processes that get created by calling the function $\textsf{forkthem()}.$ This can be given by the following equation:

  • $n > 0:  \text{T}(n) = 2 \text{T}(n-1) + 1$
  • $n = 0:  \text{T}(0) = 0$

where $\text{T}(n)$ is the number of processes created by the function. To see why this is the case, consider what happens when the function is called. The first statement calls the system call $\textsf{fork()}$ which creates a child in addition to the caller. Both the caller and the child then execute a recursive call to $\textsf{forkthem()}$ with an argument set to $n-1.$ Therefore, a call to $\textsf{forkthem()}$ creates one process of its own, and then is responsible for all the children that will get created by the function with $n-1.$ The solution to the recurrence equation is $2^n - 1.$

edited by
0 votes
0 votes

If the code is run, the function forkthem() will be called with the parameter n set to 5. Inside the function, the code checks whether n is greater than 0. Since 5 is greater than 0, the code will execute the following lines:

fork();
forkthem(n-1);
 

The fork() function creates a new process, which is a copy of the current process. This means that after the first call to fork(), there will be two processes running the same code. Each of these processes will then call forkthem() again, with n set to 4.

Since 4 is still greater than 0, the fork() function will be called again, creating two more processes. This means that there are now four processes running the same code. Each of these processes will call forkthem() again, with n set to 3.

This process will continue until n is no longer greater than 0. Since n is decremented by 1 each time forkthem() is called, the value of n will eventually become 0. At this point, the code inside the if statement will not be executed, and the recursive calls to forkthem() will stop.

In total, the code will create 2^5 = 32 processes.

Answer: