Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Fork (system call)

From Wikipedia, the free encyclopedia
(Redirected fromClone (Linux system call))
In computing, an operation whereby a process creates a copy of itself

Incomputing, particularly in the context of theUnix operating system andits workalikes,fork is an operation whereby aprocess creates a copy of itself. It is an interface which is required for compliance with thePOSIX andSingle UNIX Specification standards. It is usually implemented as aC standard librarywrapper to the fork, clone, or othersystem calls of thekernel. Fork is the primary method of process creation on Unix-like operating systems.

Overview

[edit]

Inmultitasking operating systems, processes (running programs) need a way to create new processes, e.g. to run other programs. Fork and its variants are typically the only way of doing so in Unix-like systems. For a process to start the execution of a different program, it first forks to create a copy of itself. Then, the copy, called the "child process", makes any environment changes the child will need and then calls theexec system call to overlay itself with the new program: it ceases execution of its former program in favor of the new. (Or, in rarer cases, the child forgoes theexec and continues executing, as a separate process, some other functionality of the original program.)

The fork operation creates a separateaddress space for the child. The child process has an exact copy of all the memory segments of the parent process. In modern UNIX variants that follow thevirtual memory model fromSunOS-4.0,copy-on-write semantics are implemented and the physical memory need not be actually copied. Instead,virtual memory pages in both processes may refer to the same pages ofphysical memory until one of them writes to such a page: then it is copied. This optimization is important in the common case where fork is used in conjunction with exec to execute a new program: typically, the child process performs only a small set of actions before it ceases execution of its program in favour of the program to be started, and it requires very few, if any, of its parent'sdata structures.

When a process calls fork, it is deemed theparent process and the newly created process is its child. After the fork, both processes not only run the same program, but they resume execution as though both had called the system call. They can then inspect the call'sreturn value to determine their status, child or parent, and act accordingly.

The history of fork dates back to the 1960s as one of the earliest references to a fork concept appeared inA Multiprocessor System Design byMelvin Conway, published in 1962.[1] Conway's paper motivated the implementation byL. Peter Deutsch of fork in theGENIE time-sharing system, where the concept was borrowed byKen Thompson for its earliest appearance[2] inResearch Unix.[3][4] Fork later became a standard interface inPOSIX.[5]

Technical

[edit]

Example

[edit]

The following variant of the"Hello, World!" program demonstrates the mechanics of thefork system call in theC 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 asheader inclusions has been omitted.

#include<stdio.h>#include<stdlib.h>#include<unistd.h>intmain(void){pid_tpid=fork();if(pid==-1){perror("fork failed");returnEXIT_FAILURE;}elseif(pid==0){printf("Hello from the child process!\n");returnEXIT_SUCCESS;}else{intstatus;waitpid(pid,&status,0);}returnEXIT_SUCCESS;}

What follows is a dissection of this program.

pid_tpid=fork();

The first statement inmain calls thefork system call to split execution into two processes. The return value offork is recorded in a variable of typepid_t, which is the POSIX type for process identifiers (PIDs).

if(pid==-1){perror("fork failed");returnEXIT_FAILURE;}

Minus one indicates an error infork: no new process was created, so an error message is printed.

Iffork was successful, then there are now two processes, both executing themain function from the point wherefork has returned. To make the processes perform different tasks, the program mustbranch on the return value offork to determine whether it is executing as thechild process or theparent process.

elseif(pid==0){printf("Hello from the child process!\n");returnEXIT_SUCCESS;}

In the child process, the return value appears as zero (which is an invalidprocess identifier). The child process prints the desired greeting message, then exits. (For technical reasons, the POSIX_exit function must be used here instead of the C standardexit function.)

else{intstatus;waitpid(pid,&status,0);}

The other process, the parent, receives fromfork the process identifier of the child, which is always a positive number. The parent process passes this identifier to thewaitpid system call to suspend execution until the child has exited. When this has happened, the parent resumes execution and exits by means of thereturn statement.

Communication

[edit]

The child process starts off with a copy of its parent'sfile descriptors.[5] Forinter-process communication with data exchange and synchronization between parent and child processes,pipes can be used.[6] The parent process will often create one or severalpipes, and then after forking the processes will close the ends of the pipes that they do not need.[6] To share the same variable between the parent and child processes,memory mapping orshared memory must be used.[7]

Variants

[edit]

Vfork

[edit]

Vfork is a variant of fork with the samecalling convention and much the same semantics, but only to be used in restricted situations. It originated in the3BSD version of Unix,[8][9][10] 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[11] and was replaced byposix_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 thememory 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 nocopy-on-write semantics;[11] 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 toundefined behavior.[11] 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,[citation needed] because the memory sharing that it causes is error-prone:

Vfork does not copy page tables so it is faster than the System Vfork implementation. But the child process executes in the same physical address space as the parent process (until anexec orexit) and can thus overwrite the parent's data and stack. A dangerous situation could arise if a programmer usesvfork incorrectly, so the onus for callingvfork lies with the programmer. The difference between the System V approach and the BSD approach is philosophical: Should the kernel hide idiosyncrasies of its implementation from users, or should it allow sophisticated users the opportunity to take advantage of the implementation to do a logical function more efficiently?

— Maurice J. Bach[12]

Similarly, the Linuxman page for vfork strongly discourages its use:[8][failed verificationsee discussion]

It is rather unfortunate that Linux revived this specter from the past. The BSD man page states: "This system call will be eliminated when proper system sharing mechanisms are implemented. Users should not depend on the memory sharing semantics of vfork() as it will, in that case, be made synonymous to fork(2)."

Other problems withvfork includedeadlocks that might occur inmultithreaded programs due to interactions withdynamic linking.[13] As a replacement for thevfork interface, POSIX introduced theposix_spawn family of functions that combine the actions of fork and exec. These functions may be implemented as library routines in terms offork, as is done in Linux,[13] or in terms ofvfork for better performance, as is done in Solaris,[13][14] but the POSIX specification notes that they were "designed askernel operations", especially for operating systems running on constrained hardware andreal-time systems.[15]

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 theNetBSD operating system for performance reasons.[9]

Some embedded operating systems such asuClinux 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

[edit]

ThePlan 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 astack segment, which is unique to each process),environment variables and the filesystem namespace;[16] this makes it a unified interface for the creation of both processes andthreads within them.[17] BothFreeBSD[18] andIRIX adopted the rfork system call from Plan 9, the latter renaming it "sproc".[19]

Clone

[edit]

clone is a system call in theLinux kernel that creates a child process that may share parts of its executioncontext 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 aspthreads, implemented on top of clone). The "separate stacks" feature from Plan 9 and IRIX has been omitted because (according toLinus Torvalds) it causes too much overhead.[19]

Forking in other operating systems

[edit]
icon
This sectionrelies largely or entirely on asingle source. Relevant discussion may be found on thetalk page. Please helpimprove this article byintroducing citations to additional sources.
Find sources: "Fork" system call – news ·newspapers ·books ·scholar ·JSTOR
(February 2015)

In the original design of theVMS 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.[citation needed] 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. Thespawn metaphor was later adopted in Microsoft operating systems (1993).

The POSIX-compatibility component ofVM/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.[20] This is essentially avfork labelled as afork. (This applies to the CMS guest operating system only; other VM guest operating systems, such as Linux, provide standard fork functionality.)

See also

[edit]

References

[edit]
  1. ^Nyman, Linus (25 August 2016). "Notes on the History of Fork and Join".IEEE Annals of the History of Computing.38 (3):84–87.doi:10.1109/MAHC.2016.34.
  2. ^"s3.s from Research UNIX".GitHub. 1970.
  3. ^Ken Thompson andDennis Ritchie (3 November 1971)."SYS FORK (II)"(PDF).UNIX Programmer's Manual.Bell Laboratories.
  4. ^Ritchie, Dennis M.; Thompson, Ken (July 1978)."The UNIX Time-Sharing System"(PDF).Bell System Tech. J.57 (6). AT&T:1905–1929.doi:10.1002/j.1538-7305.1978.tb02136.x. Retrieved22 April 2014.
  5. ^abfork – System Interfaces Reference,The Single UNIX Specification, Version 5 fromThe Open Group
  6. ^abpipe – System Interfaces Reference,The Single UNIX Specification, Version 5 fromThe Open Group
  7. ^"shmat()".Linux man page. Retrieved2025-07-12.
  8. ^abvfork(2) – Linux Programmer'sManual – System Calls from Manned.org
  9. ^ab"NetBSD Documentation: Why implement traditional vfork()".NetBSD Project. Retrieved16 October 2013.
  10. ^"vfork(2)".UNIX Programmer's Manual, Virtual VAX-11 Version. University of California, Berkeley. December 1979.
  11. ^abcvfork – System Interfaces Reference,The Single UNIX Specification, Version 3 fromThe Open Group
  12. ^Bach, Maurice J. (1986).The Design of The UNIX Operating System. Prentice–Hall. pp. 291–292.Bibcode:1986duos.book.....B.
  13. ^abcNakhimovsky, Greg (May 2006)."Minimizing Memory Usage for Creating Application Subprocesses".Oracle Technology Network.Oracle Corporation. Archived fromthe original on Sep 22, 2019.
  14. ^The OpenSolaris posix_spawn() implementation
  15. ^posix_spawn – System Interfaces Reference,The Single UNIX Specification, Version 5 fromThe Open Group
  16. ^fork(2) – Plan 9 Programmer's Manual, Volume 1
  17. ^intro(2) – Plan 9 Programmer's Manual, Volume 1
  18. ^rfork(2) – FreeBSD System CallsManual
  19. ^abTorvalds, Linus (1999)."The Linux edge".Open Sources: Voices from the Open Source Revolution. O'Reilly.ISBN 978-1-56592-582-3.
  20. ^"z/VM > z/VM 6.2.0 > Application Programming > z/VM V6R2 OpenExtensions POSIX Conformance Document > POSIX.1 Conformance Document > Section 3. Process Primitives > 3.1 Process Creation and Execution > 3.1.1 Process Creation". IBM. RetrievedApril 21, 2015.
Retrieved from "https://en.wikipedia.org/w/index.php?title=Fork_(system_call)&oldid=1326191416#Clone"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp