First, fork
1. Calling methods
#include <sys/types.h>
#include <unistd.h>
pid_t fork (void);
Returned correctly: The process number of the child process is returned in the parent process, and 0 is returned in the child process
Error return: 1
A child process is a copy of the parent process. That is, the child process obtains a copy of the data segment and the stack segment from the parent process, which needs to allocate new memory, whereas for read-only snippets, it is usually accessed using shared memory. When Fork returns, both the child process and the parent process begin execution from the point where the fork function is called.
The difference between a parent and a child process is that the return value of fork is different-the return value in the parent process is the process number of the child process, and the child process is 0
2. Purpose of the fork function call
⑴ a process wants to replicate itself, so the parent-child process can execute different pieces of code at the same time.
⑵ process wants to execute another program
Second, vfork
1. Calling methods
Exactly the same as the fork function
#include <sys/types.h>
#include <unistd.h>
pid_t fork (void);
Returned correctly: The process number of the child process is returned in the parent process, and 0 is returned in the child process
Error return: 1
2. Purpose of the Vfork function call
The process created with Vfork is primarily intended to execute an additional program with the EXEC function, which is the same as the second use of fork
The difference between fork and vfork
1. Fork to copy the data segment of the parent process, while Vfork does not need to fully copy the data segment of the parent process, and the child process shares the data segment with the parent process before the child process calls exec and exit
2. Fork does not restrict the execution order of the parent-child process, whereas in the vfork call, the child process runs first, the parent process hangs until the child process calls exec or exit, and the order of the parent-child process is no longer restricted
Iv. ending a child process
End child process without exit (0), instead of using _exit (0). This is because _exit (0) does not perform any operations on the standard I/O stream at the end of the process. Exit (0) closes all standard I/O streams for the process.
Linux fork function and vfork function