edited by
533 views
6 votes
6 votes

A process executes the following segment of code :

#include <stdio.h>
#include <unistd.h>
int main()
{
    fork();
    fork() && (fork() || fork());
    printf("GO 2020");
}

The number of times “$\text{GO 2020}$” will be printed is _______

edited by

2 Answers

Best answer
7 votes
7 votes

There are two concepts here, short circuit rule in C and fork in OS.

By short circuit rule in C, if the first operand of logical AND $(\&\&)$ is $0,$ the second operand won't be evaluated. Similarly, if the first operand of logical OR $(||)$ is $1.$

Now, fork(), copies the current process image and creates a child process which starts executing from the next instruction onward. fork() returns the child process id to the parent and 0 to the child process.

Now, let's trace the given code.

#include <stdio.h>
#include <unistd.h>
int main()
{
    fork(); //2 processes after this
    fork1() && (fork2() || fork3());

    printf("GO 2020");
}


fork1 will create $4$ processes in total from the $2$ processes executing them.

Only 2 of these will execute the RHS of $\&\&$ as for the other $2$ fork1 calls return $0.$

Now, fork2 will create $2$ child processes from the $2$ parent ones executing it. These $2$ child processes will have return value non zero and so skip the fork3 call. The two parents will have the return value $0$, and only those $2$ will execute fork3 creating $2$ new processes. Thus we get in total $4+2+2=8$ processes which all will print "GO 2020" once each. So, the correct answer is $8.$

selected by
2 votes
2 votes

short circuit is considered*

Answer:

Related questions

7 votes
7 votes
1 answer
1
gatecse asked Nov 15, 2020
529 views
A process executes the following segment of code :if(fork() && fork() || fork()){ printf("GATE2021"); }The number of times “$\text{GATE2021}$” will be printed is ____...
4 votes
4 votes
1 answer
3
2 votes
2 votes
1 answer
4
gatecse asked Nov 15, 2020
104 views
Processes in an operating system can be in any of the following states. Choose the proper matching for the given table.$\begin{array}{|l|l|l|}\hline& \textbf{Process Stat...