When we create a process in Linux, there are three commonly used commands to achieve this goal: fork
, exec
and wait
. Here is a detailed explanation of these three commands:
1. fork command:fork
The command is used to create a new process. The new process is a copy of the current process (parent process). It inherits the code, data, file descriptors, process context and other information of the parent process from the parent process. The new process and the parent process execute fork
the code following the command at the same time, so they can perform different operations on different branches.
fork
The command has no parameters and its syntax is as follows:
#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
After successfully calling fork
the command, it returns twice: once in the parent process, returning the PID (process ID) of the newly created child process, and once in the child process, returning 0. Returns -1 on failure.
2. exec command:exec
The command is used to execute a new program in the current process. When the command is called exec
, the code and data of the current process are replaced with the code and data of the new program, but information such as the process's PID and file descriptor remain unchanged. This enables starting a new program in the current process without creating a completely new process.
exec
There are multiple variants of the command, such as execl
, execv
, execle
, execve
etc., which can pass information such as command line parameters and environment variables according to different needs.
3. wait command:wait
The command is used by the parent process to wait for the end of the child process. When the parent process creates a child process, if you want to continue executing the code of the parent process after the child process ends, you can use the wait
command. wait
The command suspends the parent process until the child process terminates. If the child process has terminated, wait
the command returns immediately.
wait
The command has no parameters and its syntax is as follows:
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
Among them, status
the parameter is used to receive the termination status of the child process, which can be used to determine the exit status of the child process.
To sum up, fork
the command is used to create a new process, exec
the command is used to execute a new program in the current process, and wait
the command is used for the parent process to wait for the end of the child process. The combination of these three commands enables complex process management and control.