3,442 views

A process execute the code:

main()
{
fork();
fork() && fork() || fork();
fork();
printf("Hi");
}  

The number of times "Hi" will be printed is

$Ans: 20$

$\left((fork()\ \&\&\ fork() )\ ||\ fork() \right)$

$(p,c4,c8,c2,c6,c1,c5,c9,c3,c7)\times 2=20$

Basic points : -

1) && ===> if left side operand evaluates to 0 then right side operator doesn't evaluate

2) ||   ===> if left side operand evaluates to 1 then right side operator doesn't evaluate

3) fork() ====> Doubling the processes ( one parent copy and one child copy )

4) Precedence of && is grater than precedence of ||

fork() && fork() || fork() equivalent to  ( fork() && fork() ) || ( fork() ) , note that result of this statement doesn't used for next statement

for better clarity of image https://drive.google.com/drive/folders/1aji_OQGkDY9atCk6zwGhl5dYeMWXMm-c

if(fork())  \\ P>0 , C2=0 , C1>0 , C3=0
{
if(fork());  \\ (P>0 , C4=0) , (C1>0 , C5=0)
else
fork(); \\ (C4>0 , C6=0) , (C5>0 , C7=0)
}
else
fork(); 

in the code written by soumya

yes, that I was telling. How it could be correct, I am not getting

can u explain a bit?

now i understood, your problem, how this equivalent code written?

fork() && fork() || fork();

e1 && e2 || e3 ; ===> ( ( e1 && e2 ) || ( e3 ) )

first e1 executed, if it is false then e2 can't executed, go to e3

first e1 executed, if it true, then

1) e2 executed if it is true, then e3 can't executed

2) e2 executed if it is false, then e3 executed

if( e1 )

{

}

else

{

e3;

}

if(e1)

{

if(e2)

{

}

else

{

e3;

}

}

else

{

e3;

}

if(fork())

{

if(fork())

{

}

else

{

fork();

}

}

else

{

fork();

}

remaining code written as it is