fork

for(i=1;i<=3;i++)
{
fork();
printf("*");
}
How many times * is printed?

please explain;;

9Comments
Akanksha Bhardwaj @akanksha13 12 Sep 2016 10:36 am

Is the answer 11?

Shobhit @sudsho 12 Sep 2016 11:01 am

no i think it should be 8 since each fork call creates 2^n-1 processes and each time 2^n printing will be done..not sure dats why asked;;

Akanksha Bhardwaj @akanksha13 12 Sep 2016 10:07 pm

Do you have the answer ? I'm not sure if the answer is 8 or 11!

Vivek Vikram Singh @vivek14 13 Sep 2016 02:14 am

Tricky problem.

Please search for Fork() bomb.

Vivek Vikram Singh @vivek14 14 Sep 2016 10:22 pm

#include #include int main() { int i; for (i=0; i<3; i++) { pid_t pid = fork(); if (pid == 0) printf("parent:[%d] current:[%d] i=%d\n", getppid(), getpid(), i); else printf("FORK Failed for current: %d\n", getpid()); printf("*\n"); } printf("HI \n"); return 0; }

Akanksha Bhardwaj @akanksha13 13 Sep 2016 09:41 am

I think * would be printed 24 times in this case...

Lovely @cse23 14 Sep 2016 10:34 am

it should be 14 times

for  i = 1: fork() is called which will create one child process. so we have two process

parent (let c1) and child(let c2)

hence 2 times * will print

at i=2 : p1 will again create one child let c11, and c21 will create its child let c11

so we have four process : c1, c12, c2, c21

so four times * will print

at i=3: c1 will create its child let c11, c12 will create c121, c2 will craete c21 and c21 will create c21

so we have total 2^3 = 8 processes

hence * is printed 8 times

total no. of times * printed =2+4+8

                                        =14

rachapalli vinay kumar @vinayrachapalli 18 Sep 2016 07:57 pm

I got 13,

but when I executed, it prints only 9.

http://ideone.com/myUI9N

Rahul @rahul55523 21 Sep 2016 07:38 pm

Answer is 13 .

Fork() will create a new child process .Child process will start their execution at the next statement following the fork() call. Above Image shows the solution...