edited by
5,479 views
6 votes
6 votes
#include <stdio.h>
#include <unistd.h>
int main() {
    int i;
    for(i=1;i<=3;i++) {
        fork();
        printf("*");
    }
    return 0;
}



how many times * will be printed ?...is it 11?

edited by

4 Answers

Best answer
12 votes
12 votes

The above program is same as 

  fork();

  printf("*");

  fork();

  printf("*");

  fork();

printf("*");

; 

 1st fork at root, 2nd fork at level 1,3rd fork at level2

 14 is the ans.

But answer can be more than 14, due to printf buffer also being copied as a result of fork.

selected by
5 votes
5 votes

Here fork() is called 3 times through the loop from i=1 to 3 . each time * gets printed .

So, total number of process created :

(21 - 1 ) + 1 =1 + 1 = 2  .. at first level 

( 22 - 1) + 1 = 3+1 = 4 ... at 2nd level

(23-1)+1 =7 + 1 = 8 ...  at 3rd level

so total process created 2+4+8 = 14 

1 votes
1 votes

By using the formula Total processesd will be created will be 2n

first fork will create 2 processes so 2-"*"

By the second fork there will be 4 processes so 4-"*"

So for the three forks total processes will be created will be 8 so 8 "*"

Total 8+4+2=14 is the answer

Answer:

Related questions

2 votes
2 votes
3 answers
2
Philosophical_Virus asked Dec 10, 2023
768 views
Int main (){fork();printf("a");fork();printf("b");return 0;}How many distinct outputs are possible of above code? And also give outputs
3 votes
3 votes
1 answer
3
24aaaa23 asked Oct 1, 2023
723 views
Consider the following code segment :int main (void) { for (int i=2; i<=5; i++) { fork( ); }printf (“GOCLASSES”);How many times “GOCLASSES” is printed by the ab...
0 votes
0 votes
0 answers
4