A detailed explanation of the execution of fork in Linux

Time:2020-2-26

A detailed explanation of the execution of fork in Linux

Let’s take a look at a fork program

int main()
{
   pid_t pid;
 
   Statement a;   
   pid = fork();
   Statement B;
}

1. When the program runs to PID = fork(), the process immediately splits into two processes, which are called parent process and child process, The child process is a copy of the parent process. The copy means that the child process copies the data space, heap and stack of the parent process to itself. This requires that the child process be allocated the same storage space as the parent process in memory. In this way, the parent and child processes have the same data, but they do not share the storage space. They only share the body segment.

2. APUE2: the fork function is called once, but it returns twice. The only difference between the two returns is that the return value of the child process is 0, and the return value of the parent process is the process ID of the child process. It’s always hard to understand the sentence “call once, return twice”. I think it might be better to understand this: the fork function is called once, but executed twice, the parent process once returns the process ID of the child process, and the child process once returns 0

3. After the fork is finished, the child process and the parent process continue to execute the statement after the fork call. Is the parent process executed first or the child process executed first? APUE2 gives the answer: Generally speaking, it is uncertain whether the parent process executes first or the child process executes first after the fork. This depends on the scheduling algorithm used.

Thank you for reading, hope to help you, thank you for your support!