Fork-exec

Fork-exec is a commonly used technique in Unix whereby an executing process spawns a new program. 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. This is probably of limited use, so the child usually transfers to another program using the system call exec().

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. Otherwise, the parent can ignore the child process and continue executing as it normally would; to prevent the child becoming a zombie it should wait on children at intervals or on SIGCHLD.

When the child process calls exec(), all data in the original program is lost, and replaced with a running copy of the new program. This is known as overlaying. Although all data is replaced, the file descriptors that were open in the parent are closed only if the program has explicitly marked them close-on-exec. This allows for the common practice of the parent creating a pipe prior to calling fork() and using it to communicate with the executed program.

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

See also

References