C programming in Linux system to create the function fork of parsing

  • 2020-04-01 21:36:17
  • OfStack

Recently, looking at inter-process communication, I saw the fork() function, although it has been used before. This time, I thought it further. It is summarized as follows:

1. The function itself

(1) header files

# include< Unistd. H>
# include< Sys/types. H>

(2) function prototype

Pid_t fork (void);
Pid_t is a macro definition that is essentially an int defined in #include< Sys/types. H> C)
Return value: if successfully called once, return two values, child process return 0, parent process return child process ID; Otherwise, an error returns -1

(3) function description

An existing process can create a new process by calling the fork function. The new process created by fork is called the child process. The child process is the parent process A copy of the , which gets a copy of the parent process's data space, heap, stack, and other resources. Note that the child process holds a "copy" of the above storage space, which means the parent and child processes Do not share These storage Spaces, Child processes have a separate address space .

2. Code execution interpretation

(1) the code is shown in the following figure

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201304/201304110937062.png ">

(2) analysis

According to the knowledge of operating system, Process is the basic unit of system resource allocation, Therefore, the child process and the parent process do not share the process resource space. Until line 8 of the code snippet is executed, there is only the default main process on the system. After executing line 8 of the code snippet, you have two processes in the system, the main process and the child process created by it.

When a child process is created, the fork() function returns two values. The parent process returns the child process ID. Resource space is shown as follows:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201304/201304110937063.png ">

After the fork() function is executed, the main process generates a copy of the resource space for the parent process. The pid in the main process is the pid of the child process (pid> 0), the pid in the child process is 0.

After the fork() function, both the parent and child processes execute on the next line, line 9. Pid> in the main process; Else if(pid> 0) section of code, child process pid=0, can execute else if(pid==0) section of code.

(3) the code execution results are as follows:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201304/201304110937064.png ">

So, "Before the fork..." Only once." After the fork..." It was executed twice.

The specific execution result may be different depending on the process scheduling, and the following four output orders may be different. But the first output must be "Before the fork..." ).


Related articles: