5,783 views
9 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
12 12 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
Position:
Show:

Related questions

3 3 votes
1 answers 1 answer
3.9k
3.9k views
1 1 vote
2 2 answers
2.6k
2.6k views
♥_Less asked Jan 12, 2018
2,607 views
What is the number of child process created ?Answer given was 63, BUT i am getting 9 !
4 4 votes
2 2 answers
428
428 views
GO Classes asked Jul 15
428 views
Consider the following C program. Assume that every $\texttt{fork()}$ call succeeds.int main(void) { unsigned long int i; for (i = 0; i < 6; i++) if (fork() >= 0) continu...
2 2 votes
1 1 answer
288
288 views
GO Classes asked Jul 15
288 views
Assume that every $\texttt{fork()}$ call succeeds.int main() { int a = 0; int rc = fork(); a++; if (rc == 0) { rc = fork(); a++; } else { a++; } printf("a is %d\n", a); }...