// start from parent process consider it 1st process
if(fork()&& fork()) // 2 child process created
{
fork(); // 1 child process created
} // in total 1+2+1= 4 process created ( among which 1 parent and 3 child process )
from 1 parent process
if( fork() || fork() ) // 2 child process is created here from above parent process ,
// it is short circuit so in case of OR (||), after evaluation of left operand, right operand will be evaluated only if left operand evaluates to zero. But here left operand gives value 2( 21 = 2 by using the formula {2n -1 }+1 where n =1 ) so right operand is not evaluated.
{
fork(); // 2 child process is created
fork(); // again 2 child process is created
} // for each of fork() call in OR (||) 4 child process created , there are 2 fork() so total 4+4 = 8 child process created
// so in total ( 2+2) + (2 +2) = 8 [ for each fork() call in if() condition created 4 child process so total 4+4 = 8 child process ]
Total number of process created = 4 * ( 1+8) = 4 * 9 = 36 [add 1 for parent process ]
so total 36 times " XYZ " will be printed .
The tree would be like this :
P1 -- parent .. P1 is 1st process
/ \
P2 C1 -- C1 is 2 nd process
/ \
P3 C2 --- ... C2 is 3rd process
/ \
P4 C3 --- ... C3 is 4 th process
/ \ // if ( fork()&& fork()) { fork(); } part completes; total 4 process created( P1, C1, C2,C3 )
C4 C5 // if (fork() || fork()) part starts,first fork() creates 2 child process C4 & C5
/ \ / \
C6 C7 C8 C9 // executing fork(); fork();
/ \ / \ / \ / \
C10 C11 C12 C13 C14 C15 C16 C17
// total 8 leaves , for each fork() call in if(fork() || fork() ) part 4 child process is created
so total process created 1 + 8 = 9 [ 8 leaves + P4 ]
for each 3 process ( C1, C2, C3,) 8 child process would be created as same like P4 .
Hence total process would be = 4 * ( 8+1) = 4 * 9 = 36