Encyclopedia  |   World Factbook  |   World Flags  |   Reference Tables  |   List of Lists     
   Academic Disciplines  |   Historical Timeline  |   Themed Timelines  |   Biographies  |   How-Tos     
Sponsor by The Tattoo Collection
Fork (computing)
Main Page | See live article | Alphabetical index

Fork (computing)

A fork, when applied to a programming language, is when a subroutine creates a copy of itself, which then acts as a "child" of the original subroutine, now called the "parent". More generally, a fork in a multithreading environment means that a thread of execution is duplicated.

Under Unix and Unix-like operating systems, the parent and the child operations are selected by use of the return value of fork().


Here is some sample C programming language code to illustrate the idea of forking. The code that is in the "Child process" and "Parent process" sections are executed simultaneously.

  int i, pid;
  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);
     _exit(0); //Note the differing exit call.
  else if(pid > 0)
     /* Parent process:
      * Otherwise, we are in the parent process.
      * Again we count up to ten.
     int i;
     for(i=0; i < 10; i++)
        printf("parent: %d\
", i);
     // Error checking: if we couldn't fork.
     fprintf(stderr, "couldn't fork");

This code will print out 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

The order of each output is determined by the kernel.

See also