-2

from the man page of fork i read fork create duplicate of parent process. But not able to understand why below program printf execute 8 times. I read Working of fork() in linux link also.

#include <stdio.h>
int main()
{
    fork();
    fork();
    fork();
    printf("process\n");
}
Community
  • 1
  • 1
sujin
  • 2,813
  • 2
  • 21
  • 33

2 Answers2

3

Fork works like a binary tree. So its always 2^x number of processes on every x number of fork calls.

Lets understand with your example.

First fork() call:

When the first fork() is called. The parent process creates a new process. So we have 2 threads.

Second fork() call:

At this point we have two processes(main process and a new created process).These two threads will call second fork individually and create 2 new processes each. so we have 4 threads.

You might have got the idea by now. Every time a fork() is encountered all the processes create their respective child processes(double themselves).

enter image description here

Sorter
  • 9,704
  • 6
  • 64
  • 74
  • 1
    -1. Lifted from [this](http://stackoverflow.com/a/8768918/2235132) answer without attribution. – devnull Jan 13 '14 at 09:45
  • 1
    Sir, I haven't. I know it works like binary tree and I was providing a distinct explanation according to OP's question. And the image is the first result in google image search for `fork binary tree` FYI. Kindly do not down vote in such abrupt manner. – Sorter Jan 13 '14 at 09:50
  • Fair enough; downvote reversed. – devnull Jan 13 '14 at 09:51
3

In general for n forks in this manner will execute the next statements (in this case printf) 2^n times. Here is how:

|
+-fork()----------------------------------+
|                                         |
+-fork()-------------+                    +-fork()-------------+
|                    |                    |                    |
+-fork()---+         +-fork()---+         +-fork()---+         +-fork()---+
|          |         |          |         |          |         |          |
print()    print()   print()    print()   print()    print()   print()    print()
Dipto
  • 2,720
  • 2
  • 22
  • 42