From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

Fork–exec is a commonly used technique in Unix whereby an executing process spawns a new program.


Dennis M. Ritchie created fork-exec.[1] fork() is the name of the system call that the parent process uses to "divide" itself ("fork") into two identical processes. After calling fork(), the created child process is an exact copy of the parent except for the return value of the fork() call. This includes open files, register state, and all memory allocations, which includes the program's executable code. In some cases the two continue to run the same binary, but often one (usually the child) switches to running another binary executable using the exec() system call.

When a process forks, a complete copy of the executing program is made into the new process; this new process (which is a child of the parent) has a new process identifier (PID). The fork() function returns the child's PID to the parent, while it returns 0 to the child, in order to allow the two identical processes to distinguish one another.

The parent process can either continue execution or wait for the child process to complete; the child, after discovering that it is the child, replaces itself completely with another program, so that the code and address space of the original program are lost.

If the parent chooses to wait for the child to die, then the parent will receive the exit code of the program that the child executed. To prevent the child becoming a zombie the parent should call wait on its children, either periodically or upon receiving the SIGCHLD signal, which indicates a child process has terminated.

One can also asynchronously wait on their children to finish, by using a signal handler for SIGCHLD, if they need to ensure everything is cleaned up. Here's an example of a signal handler that catches any incoming SIGCHLD signals and handles multiple concurrent signals received.

  void cleanup(int signal) {
    int status;
    while (waitpid((pid_t) (-1), 0, WNOHANG) > 0) {}


Microsoft Windows does not support the fork-exec model, as it does not have a system call analogous to fork(). The spawn() family of functions declared in process.h can replace it in cases where the call to fork() is followed directly by exec().


— Jack Hammons of Microsoft[2]


  2. ^