Alex Goft Alex Goft - 4 months ago 16
C Question

Trouble understanding fork() output

Assuming that a process with pid=1 runs the following code:

int a = fork();
int b = fork();
printf(“a: %d, b: %d\n”, a, b);


(And assume that pid id is incremented by 1)

A possible output is:

a:2, b:3
a:2, b:0
a:0, b:4
a:0, b:0


Im having some hard time understanding the output of the above code, specially why
a:0, b:4
and
a:2, b:3
.

Thank you.

Answer

You know that

The return value is the zero in the child and the process-id number of the child in the parent, or -1 upon error.

So, let's see step by step what's happening here.

When fork() is called, it creates a new child with id n, then returns in the child 0 and in the parent n.

So let's suppose our process as pid 1, when the first fork() is called it creates a process with pid 2, then returns to a a value. a will have value 0 in the process 2 (the child), and will have value 2 in process 1 (the parent).

Then each process will call fork() and assign the return value to b in the parent process. In the child, b will have value 0.

Anyway, I think this schema will simplify the comprehension:

The main starts:

|
|
int a = fork(); // It creates a new process, and the old one continues going
|
|-------------------------|
a = 2; /* Parent */       a = 0; // Child
|                         |
|                         |
int b = fork();           int b = fork(); // Each one create a new process
|                         |
|                         |-----------------------------|
|                         /* Child -> Parent */         // Child -> Child
|                         a = 0; b = 4;                 a = 0; b = 0
|
|
|
|
|-----------------------------|
/* Parent -> Parent */        // Parent -> Child
a = 2; b = 3;                 a = 2, b = 0; 
Comments