in Operating System retagged by
871 views
0 votes
0 votes
#include <stdio.h>
void main()
{
    int i = 3;
    while(i>0)
    {
        i--;
        if(fork()||fork())
        {
            printf("Hi");
        }
    }
}

How many times “Hi” will be printed ??

 

#include <stdio.h>
void main()
{
    int i = 2;
    while(i>0)
    {
        i--;
        if(fork()||fork())
        {
            printf("Hi");
        }
    }
}

How many times “Hi” will be printed ??
in Operating System retagged by
871 views

1 comment

for first question  i=3:

for i = 2: 3 total processes  out of which 2 prints Hi and one does not. Total Hi = 2.

for i = 1: 3 processes creates 3 more process each so total created 9 out of which 2/3 prints Hi and 1/3does not. Total Hi = 2+6 = 8

for i = 0: 9 processes creates 3 more process each so total created 27 out of which 2/3 prints Hi and 1/3does not. Total Hi = 2+6+18 = 26

So total hi = 26.

similarly for second question hi printed = 8.
1
1

2 Answers

2 votes
2 votes

Let’s look at i = 1. When i=1, if condition executed one time. Let's understand what happens when $fork()||fork()$ executes.

first $fork()$ creates two children (i.e. one parent and one child). Parent gets the address of its children (i.e. process id of its children) and the child gets $0$.

Now, for each node, two children are created by the 2nd $fork()$.

Among them, first three children get executed (i.e. for the last child  $if(0||0)$ never gets executed).

The below diagram shows the execution for $i=1$

$\therefore$ total number of “Hi” printed for i=1 is $3$.

Now, for i=2, each of the leaf nodes will have the same subtree as its parent (i.e. each produces 3 “Hi” as output).

$\therefore$ total number of “Hi” printed for i=2 is $3*4=12$.

For, i=3, total “Hi” will be $12*4=48$

Code

edited by

2 Comments

Bro when parent execute fork1(), i gets id of child process which is positive value.as its get postive value i think short cricut happens for parent process becauss of "ll", and it will not execute fork2(). for i=1 i am getting hi 2 times .
0
0

When parent execute fork1(), it gets the PID of it's child and the child get PID 0. Now parent and child does not share the same local resources as before. So, when parent create a child process, they both start executing on their own address space. So, conflict should not occur.

Reference: https://www.youtube.com/live/ru-ouiqVDqc?feature=share?t=29m00s

0
0
0 votes
0 votes
for i=3 Hi will be printed 6 times

for i=2 Hi will be printed 4 times

1 comment

Can you please also elaborate how? When I try on any online compiler it prints error more than 6 times for i=3 atleast.
0
0

Related questions