Fork (system call)
≈ 7 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
In computing, fork is an operation whereby a process creates a copy of itself. It is usually implemented as a C standard library wrapper to the fork, clone, or other system calls of the kernel. For many years, fork was the primary method of process creation on Unix and Unix-like operating systems, and it remains a required interface for compliance with POSIX. Despite this, it has fallen out of favor in recent years as a result of flaws including poor performance, a lack of thread safety, and its status as a common source of security vulnerabilities.
In computing, fork is an operation whereby a process creates a copy of itself. It is usually implemented as a C standard library wrapper to the fork, clone, or other system calls of the kernel. For many years, fork was the primary method of process creation on Unix and Unix-like operating systems, and it remains a required interface for compliance with POSIX. Despite this, it has fallen out of favor in recent years as a result of flaws including poor performance, a lack of thread safety, and its status as a common source of security vulnerabilities. The following variant of the "Hello, World!" program demonstrates the mechanics of the system call in the C programming language. The program forks into two processes, each deciding what functionality they perform based on the return value of the fork system call. Boilerplate code such as header inclusions has been omitted. include include include int main(void) { pid_t pid = fork(); if (pid
-1) { perror("fork failed"); return EXIT_FAILURE; } else if (pid
0) { printf("Hello from the child process!\n"); return EXIT_SUCCESS; } else { int status; waitpid(pid, &status, 0); } return EXIT_SUCCESS; } What follows is a dissection of this program. pid_t pid = fork(); The first statement in calls the system call to split execution into two processes. The return value of is recorded in a variable of type , which is the POSIX type for process identifiers (PIDs). if (pid == -1) { perror("fork failed"); return EXIT_FAILURE; } Minus one indicates an error in : no new process was created, so an error message is printed. If was successful, then there are now two processes, both executing the function from the point where has returned. To make the processes perform different tasks, the program must branch on the return value of to determine whether it is executing as the child process or the parent process. else if (pid == 0) { printf("Hello from the child process!\n"); return EXIT_SUCCESS; } In the child process, the return value appears as zero (which is an invalid process identifier). The child process prints the desired greeting message, then exits. (For technical reasons, the POSIX function must be used here instead of the C standard function.) else { int status; waitpid(pid, &status, 0); } The other process, the parent, receives from the process identifier of the child, which is always a positive number. The parent process passes this identifier to the system call to suspend execution until the child has exited. When this has happened, the parent resumes execution and exits by means of the statement.
Variants
Vfork
Vfork is a variant of fork with the same calling convention and much the same semantics, but only to be used in restricted situations. It originated in the 3BSD version of Unix, the first Unix to support virtual memory. It was standardized by POSIX, which permitted vfork to have exactly the same behavior as fork, but was marked obsolescent in the 2004 edition and was replaced by posix_spawn() (which is typically implemented via vfork) in subsequent editions. When a vfork system call is issued, the parent process will be suspended until the child process has either completed execution or been replaced with a new executable image via one of the "exec" family of system calls. The child borrows the memory management unit setup from the parent and memory pages are shared among the parent and child process with no copying done, and in particular with no copy-on-write semantics; hence, if the child process makes a modification in any of the shared pages, no new page will be created and the modified pages are visible to the parent process too. Since there is absolutely no page copying involved (consuming additional memory), this technique is an optimization over plain fork in full-copy environments when used with exec. In POSIX, using vfork for any purpose except as a prelude to an immediate call to a function from the exec family (and a select few other operations) gives rise to undefined behavior. As with vfork, the child borrows data structures rather than copying them. vfork is still faster than a fork that uses copy on write semantics. System V did not support this function call before System VR4 was introduced, because the memory sharing that it causes is error-prone: Similarly, the Linux man page for vfork strongly discourages its use: Other problems with include deadlocks that might occur in multithreaded programs due to interactions with dynamic linking. As a replacement for the interface, POSIX introduced the family of functions that combine the actions of fork and exec. These functions may be implemented as library routines in terms of , as is done in Linux, or in terms of for better performance, as is done in Solaris, but the POSIX specification notes that they were "designed as kernel operations", especially for operating systems running on constrained hardware and real-time systems. While the 4.4BSD implementation got rid of the vfork implementation, causing vfork to have the same behavior as fork, it was later reinstated in the NetBSD operating system for performance reasons. Some embedded operating systems such as uClinux omit fork and only implement vfork, because they need to operate on devices where copy-on-write is impossible to implement due to lack of a memory management unit.
Rfork
The Plan 9 operating system, created by the designers of Unix, includes fork as a variant of a new function called "rfork" that permits fine-grained sharing of resources between parent and child processes, including the address space (except for a stack segment, which is unique to each process), environment variables and the filesystem namespace; this makes it a unified interface for the creation of both processes and threads within them. Both FreeBSD and IRIX adopted the rfork system call from Plan 9, the latter renaming it "sproc".
Clone
clone is a system call in the Linux kernel that creates a child process that may share parts of its execution context with the parent. Like FreeBSD's rfork and IRIX's sproc, Linux's clone was inspired by Plan 9's rfork and can be used to implement threads (though application programmers will typically use a higher-level interface such as pthreads, implemented on top of clone). The "separate stacks" feature from Plan 9 and IRIX has been omitted because (according to Linus Torvalds) it causes too much overhead.
Forking in other operating systems
In the original design of the VMS operating system (1977), a copy operation with subsequent mutation of the content of a few specific addresses for the new process as in forking was considered risky. Errors in the current process state may be copied to a child process. Here, the metaphor of process spawning is used: each component of the memory layout of the new process is newly constructed from scratch. The spawn metaphor was later adopted in Microsoft operating systems (1993). The POSIX-compatibility component of VM/CMS (OpenExtensions) provides a very limited implementation of fork, in which the parent is suspended while the child executes, and the child and the parent share the same address space. This is essentially a vfork labelled as a fork. (This applies to the CMS guest operating system only; other VM guest operating systems, such as Linux, provide standard fork functionality.)
See also
Fork bomb Fork–exec exit (system call) spawn (computing) wait (system call)
References
Text derived from https://en.wikipedia.org/w/index.php?oldid=1364751896 under CC BY-SA 4.0; modifications have been made.