in Operating System edited by
250 views
1 vote
1 vote
Q23. The following C program is executed on a Unix/Linux system:
 

main()
{
                 int i=0;
                 while (i<20)
                        if (i%2==0) fork();
                        i++;
                  return 0;
}
 

Calculate how many number of processes will be created after executing the above program.

Options:
1.1023
2.Infinite
3.1024
4.2048
in Operating System edited by
by
250 views

1 Answer

1 vote
1 vote
Best answer

Option (2)
The provided C program initiates an indefinite generation of processes due to the absence of braces around the while loop, which leads to the exclusion of the i++ statement from the loop's scope. Consequently, the variable i remains unaltered, and the condition i < 20 persistently holds true, resulting in an infinite loop.
Similar to fork bomb :

`while(1) fork()`
The above snippet also creates infinite child processes

Within each iteration of the loop, the fork() function is invoked when i % 2 equals 0. Since i consistently remains zero, fork() gets executed in every iteration, spawning a new process each time. This incessant process creation continues until system resources become depleted, necessitating manual termination of the program.

This behavior mirrors that of a "fork bomb," a malicious construct that exploits the fork() system call to overwhelm system resources.

In contrast, consider the modified version of the program with a for loop:

C

main() {

for(int i = 0; i < 20; i++)

if(i % 2 == 0) fork();

return 0;

}

In this rendition, the fork() function is invoked exclusively during even iterations of the loop. This is due to the fact that, in this version, the value of i is incremented before the fork() call within the loop's scope so it get updated for each child process before making another child process.So here total 1024 processes will be created once code is executed (1023 new Child processes and 1 parent process).

Consequently, the original C code theoretically generate infinite child processes and, practically, as many processes as the system's memory resources permit.
So only option (2) is correct.

edited by

Related questions