The role of fork is to replicate a new process based on an existing process, called the parent process, and the new process is called a subprocess (child process). There are a lot of processes running in the system at the same time, and these processes are copied from the beginning of a single process. An input command under the shell can run a program because the shell process calls fork to replicate a new shell process after reading the user's input command, and then the new shell process calls exec to execute the new program.
We know that a program can be loaded into memory multiple times, to be running multiple processes at the same time, for example, you can open multiple terminal windows to run/bin/bash, on the other hand, a process can execute two different programs before and after calling exec, such as entering command LS at the shell prompt, First Fork is created, the child process is still executing the/bin/bash program, and the child process calls exec to execute the new program/bin/ls, as shown in the following illustration.
First, fork system call
Include header files <sys/types.h> and <unistd.h>
function function: Create a child process
Function prototypes
pid_t fork (void);
Parameter: no parameters.
return value:
Returns the child process ID for the parent process if a child process is successfully created
If a child process is successfully created, the return value is 0 for the child process
If-1 indicates a creation failure