Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble understanding fork() output

Tags:

c

fork

pid

Let's assume that there is a process with PID = 1 and it runs the following code:

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

Let's further assume that new PIDs will be given one by one, so the second given PID will be 2, then 3 etc.

A possible output is:

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

I'm having some troubles trying to understand the output of the above code, e especially why a:0, b:4 and a:2, b:3.

like image 799
Alex Goft Avatar asked Nov 29 '22 23:11

Alex Goft


1 Answers

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; 
like image 87
rpadovani Avatar answered Dec 09 '22 09:12

rpadovani