views:

501

answers:

3

I have a c file that looks like this:

#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 
int main () 
{ 
    pid_t child_pid; 
    printf ("The PID is %d\n", (int) getpid ()); 
    child_pid = fork (); 
    if (child_pid != 0)
    { 
     printf ("this is the parent process, with PID %d\n", 
     (int)getpid()); 
     printf ("the child's PID is %d\n", (int) child_pid); 
    } 
    else 
     printf ("this is the child process, with PID %d\n", 
     (int)getpid()); 
return 0; 
}

I need to modify it to produce a a hierarchy that looks like

  • 0
    • >1
    • >2
    • >>3
    • >>4
    • >>>5

Basically a tree structure where each second child makes two new children. As far as I understand it, when I fork a process, each process will run concurrently. Adding a fork in the if statement seems to work and creates processes 0 to 2 correctly, since only the parent will create a new fork. But I have no idea how to make process 2 fork and not 1. Any ideas?

+2  A: 

Well, process 1 will be created by the first fork. Process 2 will be created by the fork inside the if-statement. So to let process 2 fork too, you fork again inside the if-statement if the second fork did not return 0.

An illustration:

if(fork) {
    // Inside process 0
    if(fork) {
        // still in process 0
    } else {
        // in process 2
        if(fork) {
          // still in process 2
        } else {
          // in prcess 3
        }
        // and so on
    }
} else {
    // Inside process 1
}
sepp2k
Thanks. This makes the concept much clearer.
pypmannetjies
+2  A: 

Children get a copy of the parent's state at the time of the fork.

So if the parent has a counter or other property then the children will see the value at the time of they were forked (but not if the parent subsequently alters it).

Will
+2  A: 

I don't know why you want to do it this way, but normally only the parent process performs the fork. This may be easier to design too. When you perform fork() inside a for-loop you'll have direct control over the processes created.

Please be aware that fork() is a relatively expensive operation, especially if you want to create many processes. More lightweight alternatives vfork and threads are available but I can not judge if they also fit your needs.

Adriaan
Any process can fork, even children. In fact, this is how fork bombs are written, with each process forking another two until the system is swamped.
paxdiablo
Thanks pax; I've updated my answer accordingly
Adriaan
It was just an exercise - I would never willingly do something so strange :)
pypmannetjies