EMZETT.
Login

fork and exec: how Unix starts programs

In short: Unix starts new programs in two steps: fork copies the running process, exec replaces the program in the copy with another.

In more detail: That is how every command in the shell starts too. The split lets you adjust things such as redirections or permissions between the two steps.

In Depth

  • fork: Creates a child process with almost identical state. The return value tells them apart: the child’s PID in the parent, 0 in the child. Thanks to copy-on-write it is cheap.
  • exec: Loads a new program into the process. The PID stays, memory and code are replaced.
  • wait: The parent waits for the child to end with wait/waitpid. If it forgets, a zombie process remains.
  • Redirection: After the fork and before exec the shell opens files (>) or pipes and sets them as input and output.
  • Windows: Has no fork, but CreateProcess, which combines both.
  • Modern alternatives: posix_spawn and vfork save effort with large processes.
  • Containers: The first process in a container is PID 1 and must reap orphaned children.

See also: processes and signals