3,256 views
9 votes
9 votes
main()
{
    if(fork()>=0)
    {
        printf("*");
        if(fork()==0)
        {
            printf("*");
    }
    else{
        //do nothing
    }
    printf("*");
}

How many number of times “*” will be printed?

 

4 Answers

Best answer
11 votes
11 votes
01.main()
02.{
03.    if(fork()>=0)
04.    {
05.        printf("*");
06.        if(fork()==0)
07.        {
08.            printf("*");
09.        }
10.        else{
11.            //do nothing
12.        }
13.        printf("*");
14.    }
15.}

Our execution is one process, So at line 1, number of processes = 1

at line 3, due to fork() statement, one more child process will be created, So at line number 3, number of processes = 2.

BASIC POINT in the view of fork(), is child process return 0, and parent process return a positive value when fork() applied.

in the line 3 :- the condition is ≥ 0 , so both P1 (parent) and P2(child) enter into if block.

line number 5 can be executed by P1 and P2 ===> No.of * prints till now = 2.

 

when P1 executes the line number 6, one more child P3, created.

But note that, condition is fork() == 0, So only P3 can enter into the line 7. but not P1

 

when P2 executes the line number 6, one more child P4, created.

But note that, condition is fork() == 0, So only P4 can enter into the line 7. but not P2.

 

So, line number 8 can be executed by P3 and P4 ===> No.of * prints till now = 2+2 = 4

 

All these 4 processes, P1,P2,P3,P4 can executes the line number 13.

So, line number 13 can be executed by All ===> No.of * prints till now = 4+4 = 8.

 

more problems on fork() concept :- https://gateoverflow.in/302831/gate2019-17?show=303821#c303821

selected by

Related questions

3 votes
3 votes
1 answer
1
1 votes
1 votes
2 answers
2
♥_Less asked Jan 12, 2018
1,742 views
What is the number of child process created ?Answer given was 63, BUT i am getting 9 !
2 votes
2 votes
3 answers
4
Philosophical_Virus asked Dec 10, 2023
765 views
Int main (){fork();printf("a");fork();printf("b");return 0;}How many distinct outputs are possible of above code? And also give outputs