First, let's take a look at the parent process and the subprocess, the previous sections on how to create a subprocess, like this, pid_t id = fork (); So we create a subprocess, but what is the return value of the fork () function? Remember here: The subprocess returns 0, the parent process returns the PID of the subprocess, and returns-1 if the creation fails. Because it is a child process created by the parent process, the child process inherits from the parent process. For example, a child process inherits the data space of the parent process, the heap, and a copy of the stack. However, does the parent-child process share the same address space? The answer is in the negative. This leads to the content of the virtual address we talked about in the previous sections. Recall:
They are the address spaces of the parent-child process, although their virtual addresses are the same, but their physical addresses are different. (This picture is described in detail in this blog, "Linux address Space")
The parent-child process does not share the storage space and only shares code snippets.
Let's look at an example:
Think about the results of this code running.
A lot of people look at this code and think it's going to output 4 statements, but it's not. Let's analyze the mystery, hehe ...
First, the parent process creates the child process, then the parent-child process prints one of its own PID, after printing the i++;i++; the parent process then recreated the child process, and the child process at the top level enters the parent process, creating the child process, so that the i=1 equivalent of the parent-child process creates 2 processes. That is, the second level creates 4 processes, so the number of processes = 2+4=6.
The results are as follows:
Is this picture a bit like a binary tree? So when i = 10.
Through the above analysis and reasoning to know that its result is this:2+2^2+2^3+......+2^10=2046
When i = N, the formula is: 2+2^2+2^3+......+2^n = 2* (1-2^n)/(1-2);