[Linux] Basic knowledge of fork function

Article directory

  • Preface
  • 1. Return value of fork
  • 2. Frequently Asked Questions
    • 1. Why does fork return 0 to the child process and the child process pid to the parent process?
    • 2. How do you understand a function returning two values?
    • 3. How can a variable have different contents?

    • 4.What does the fork function do?


Preface

First acquaintance with fork:

1.fork has two return values.

2. Code sharing between father and son processes, data space for each, private copy (realistic copy). 


 When we ran the test, we found that there was an extra process. This process is a child process branched from fork. The processes are independent of each other.

1. Return value of fork

fork()The function creates a new process, and the return value of the function is an integer. In the parent process, fork()the return value of is the PID (process ID) of the child process, while in the child process, fork()the return value of is 0.

Therefore, fork()the return value of the function can be used to determine whether the current code is running in the parent process or the child process. If fork()a non-zero value is returned, the code runs in the child process; if fork()0 is returned, the code runs in the parent process.

2. Frequently Asked Questions

1. Why does fork return 0 to the child process and the child process pid to the parent process?

Returning different return values ​​is to distinguish different execution flows from executing different code blocks. The parent process receives the pid of the child process because the parent process may have multiple child processes. In order to distinguish them, their unique pids are used as the return value, and the child process can directly use the getppid() function to obtain the pid of the parent process, so the child process returns is 0.

2. How do you understand a function returning two values?

3. How can a variable have different contents?

4.What does the fork function do?

The child process is created, the PCB is created for the child process, the child process is initialized with the fields corresponding to the parent process, and the code is shared.


Guess you like

Origin blog.csdn.net/m0_74774759/article/details/132628496