Fork (operating system)

Fork (operating system)

In computing, when a process forks, it creates a copy of itself, which is called a "child process." The original process is then called the "parent process". More generally, a fork in a multithreading environment means that a thread of execution is duplicated, creating a child thread from the parent thread.

Under Unix and Unix-like operating systems, the parent and the child processes can tell each other apart by examining the return value of the fork() system call. In the child process, the return value of fork() is 0, whereas the return value in the parent process is the PID of the newly-created child process.

The fork operation creates a separate address space for the child. The child process has an exact copy of all the memory segments of the parent process, though if copy-on-write semantics are implemented actual physical memory may not be assigned (i.e., both processes may share the same physical memory segments for a while). Both the parent and child processes possess the same code segments, but execute independently of each other.

Importance of Fork In Unix

Forking is an important part of Unix, critical to the support of its design philosophy, which encourages the development of filters. In Unix, a filter is a small program that reads its input from stdin, and writes its output to stdout. A pipeline of these commands can be strung together by a shell to create new commands. For example, one can string together the output of the find(1) command and the input of the wc(1) command to create a new command that will print a count of files ending in ".cpp" found in the current directory, as follows: $ find . -name "*.cpp" -print | wc -lIn order to accomplish this, the shell forks itself, and uses pipes, a form of interprocess communication, to tie the output of the find command to the input of the wc command. Two child processes are created, one for each command (find and wc). These child processes are overlaid with the code associated with the programs they are intended to execute, using the exec(3) family of system calls (in the above example, find will overlay the first child process, and wc will overlay the second child process, and the shell will use pipes to tie the output of find with the input of wc).

More generally, forking is also performed by the shell each time a user issues a command. A child process is created by forking the shell, and the child process is overlaid, once again by exec, with the code associated with the program to be executed.

Process Address Space

Whenever an executable file is executed, it becomes a process. An executable file contains binary code grouped into a number of blocks called segments. Each segment is used for storing a particular type of data. A few segment names of a typical ELF executable file are listed below.

* text — Segment containing executable code
* .bss — Segment containing uninitialized data
* data — Segment containing initialized data
* symtab — Segment containing the program symbols (e.g., function name, variable names, etc.)
* interp — Segment containing the name of the interpreter to be used

If you want further analysis of an ELF file you can use the "readelf" command. When such a file is loaded in the memory for execution, the segments are loaded in memory. It is not necessary for the entire executable to be loaded in contiguous memory locations. Memory is divided into equal sized partitions called pages (typically 4KB). Hence when the executable is loaded in the memory, different parts of the executable are placed in different pages (which might not be contiguous). Consider an ELF executable file of size 10K. If the page size supported by the OS is 4K, then the file will be split into three pieces (also called frames) of size 4K, 4K, and 2K respectively. These three frames will be accommodated in any three free pages in memory.

Fork and page sharing

When a fork() system call is issued, a copy of all the pages corresponding to the parent process is created, loaded into a separate memory location by the OS for the child process. But this is not needed in certain cases. Consider the case when a child executes an "execv" system call (which is used to execute any executable file from within a C program) or exits very soon after the fork(). When the child is needed just to execute a command for the parent process, there is no need for copying the parent process' pages, since execv replaces the address space of the process which invoked it with the command to be executed.

In such cases, a technique called copy-on-write (COW) is used. With this technique, when a fork is done, the parent process's pages are not copied for the child process. Instead, the pages are shared between the child and the parent process. Whenever a process (parent or child) modifies a page, a separate copy of that particular page alone is made for that process (parent or child) which performed the modification. This process will then use the newly copied page rather than the shared one in all future references. The other process (the one which did not modify the shared page) continues to use the shared version of the page. This technique is called copy-on-write since the page is copied when some process writes to it.

Vfork and page sharing

vfork is another UNIX system call used to create a new process. 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 execve() family of system calls. Even in vfork, the pages are shared among the parent and child process. But vfork does not mandate copy-on-write. 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 highly efficient when a process needs to execute a blocking command using the child process.

Application usage

On some systems, vfork() is the same as fork().

One example of the unique use of vfork() is AmigaOS operating system.

The vfork() function differs from fork() only in that the child process can share code and data with the calling process (parent process). This speeds cloning activity significantly at a risk to the integrity of the parent process if vfork() is misused.

The use of vfork() for any purpose except as a prelude to an immediate call to a function from the exec family, or to _exit(), is not advised. In particular the Linux man page for vfork strongly discourages its use: [ [http://www.linuxmanpages.com/man2/vfork.2.php VFORK ] ]

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)."

The vfork() function can be used to create new processes without fully copying the address space of the old process. If a forked process is simply going to call exec, the data space copied from the parent to the child by fork() is not used. This is particularly inefficient in a paged environment, making vfork() particularly useful. Depending upon the size of the parent's data space, vfork() can give a significant performance improvement over fork().

The vfork() function can normally be used just like fork(). It does not work, however, to return while running in the child's context from the caller of vfork() since the eventual return from vfork() would then return to a no longer existent stack frame. Be careful, also, to call _exit() rather than exit() if you cannot exec, since exit() flushes and closes standard I/O channels, thereby damaging the parent process' standard I/O data structures. (Even with fork(), it is wrong to call exit(), since buffered data would then be flushed twice.)

If signal handlers are invoked in the child process after vfork(), they must follow the same rules as other code in the child process. [UNIX Specification Version 2, 1997 [http://www.opengroup.org/pubs/online/7908799/xsh/vfork.html http://www.opengroup.org/pubs/online/7908799/xsh/vfork.html] ]

Example

Below is some sample C code to illustrate the idea of forking. The code that is in the "Child process" and "Parent process" sections is executed simultaneously in two different processes.

#include /* printf, stderr, fprintf */
#include /* _exit, fork */
#include /* exit */
#include /* errno */

int main(void){ pid_t pid = fork();

if (pid = 0) { /* Child process: * When fork() returns 0, we are in * the child process. * Here we count up to ten, one each second. */ int j; for (j = 0; j < 10; j++) { printf("child: %d ", j); sleep(1); } _exit(0); /* Note that we do not use exit() */ } else if (pid > 0) { /* Parent process: * When fork() returns a positive number, we are in the parent process * (the fork return value is the PID of the newly-created child process). * Again we count up to ten. */ int i; for (i = 0; i < 10; i++) { printf("parent: %d ", i); sleep(1); } exit(0); } else { /* Error: * When fork() returns a negative number, an error happened * (for example, number of processes reached the limit). */ fprintf(stderr, "can't fork, error %d ", errno); exit(1);

This code will print out something similar to the following: parent: 0 child: 0 child: 1 parent: 1 parent: 2 child: 2 child: 3 parent: 3 parent: 4 child: 4 child: 5 parent: 5 parent: 6 child: 6 child: 7 parent: 7 parent: 8 child: 8 child: 9 parent: 9

While the printed count from each process steadily increases from 0 to 9, the output of the two processes are intertwined according to the order in which the kernel schedules them to execute.

ee also

*Child process
*Parent process
*Fork bomb
*Fork-exec
*Exec
*Exit
*Wait

References

External links

*man|sh|fork|SUS|create a new process


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать курсовую

Look at other dictionaries:

  • Pick operating system — Company / developer Don Nelson, Dick Pick, TRW Programmed in Assembly language Initial release 1965 (GIRLS), 1973 (Reality Operating System) Marketing target Business data processing Available …   Wikipedia

  • Android (operating system) — Android …   Wikipedia

  • Exit (operating system) — A computer process terminates its execution by making an exit system call. More generally, an exit in a multithreading environment means that a thread of execution has stopped running. The operating system reclaims resources (memory, files, etc.) …   Wikipedia

  • Genera (operating system) — Genera Company / developer Symbolics OS family Lisp Machine OS Initial release 1982 …   Wikipedia

  • Mobile operating system — A mobile operating system, also known as a mobile OS, mobile software platform or a handheld operating system, is the operating system that controls a mobile device or information appliance similar in principle to an operating system such as… …   Wikipedia

  • LOCUS (operating system) — Infobox OS name = LOCUS developer = UCLA family = Unix source model = Closed source working state = Historic kernel type = Monolithic kernel license = Proprietary LOCUS was a distributed operating system developed at UCLA during the 1980s. It was …   Wikipedia

  • Ubuntu (operating system) — Ubuntu Ubuntu 11.10 (Oneiric Ocelot) Company / developer …   Wikipedia

  • Haiku (operating system) — Haiku Company / developer Haiku Project OS family …   Wikipedia

  • V (operating system) — The V operating system (sometimes written V System, not to be confused with System V) is a microkernel operating system that was developed by faculty and students in the Distributed Systems Group at Stanford University in the 1980s, led primarily …   Wikipedia

  • Overlay (operating system) — For the division of a single program to reduce memory requirements, see Overlay (programming). In operating systems, an overlay is when a process replaces itself with the code of another program. On Unix like systems, this is accomplished with… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”