Learning how to use fork()

So I'm trying to understand this 'fork()' method under linux and I'm creating a C program using it.

Basically I know how to create a chain of forks using something along the lines of:
pid_t pid;

fork();
pid =getpid();

for (i=0; i<n;i++){
printf("\n %d %d \n",i, pid);

So basically, to my understanding this creates a chain of processes. So it clones the code from a parent to a child right after FORK is called. If this is true why should it not be in the for loop since I'm creating more than one unique process? (the for loop iterates i and pid so I can have more than one process)

So how in the world would I create a binary tree with this?
This is my code to what I think would create a binary tree:
fork();
pid =getpid();

/*child process*/
if(pid == 0){
fork();
}

else{ ....

My logic behind this is, fork() and if your pid == 0 (you're a child) fork again?

It looks like I may not be fully understanding this fork method so some help on how to understand this would be great!
Hi,

Your code will generate only three process.

In general, fork will return twice one in parent process and another one in child process, both will execute the next statement after fork.

Thats why you should not put fork in loop, both the process will execute the for loop and fork many process and this one will iterate, unless you protect it with some means like fork a new process only in the parent process.

Hope this helps.

So how in the world would I create a binary tree with this?


er, you wouldn't.

a binary tree is a data structure, you are creating a fork bomb.
you don't fork for a binary tree.

there should be plenty of binary tree info if you search.

regards


Last edited on
Topic archived. No new replies allowed.