DistributedNetworks DistributedNetworks

Special File Types   «Prev  Next»
Lesson 3 Forking
ObjectiveDescribe the mechanism by which processes come into being.

Unix Fork Call

Birth, life, and death of process

All processes on a UNIX system come into being in the same way: They are cloned from an already running process. For example, suppose that a user types the command
grep yes *.c
to his or her login shell. At this point, the shell needs to start a new grep process, wait for it to finish, then generate a new output prompt and wait for the next command. The mechanism by which this occurs is called forking.

fork(), exec(), wait()

Many aspects of the behavior of UNIX processes are consequences of how they are born. Behind the scenes, the procedure looks like this:
  1. The shell process executes a system call called fork(). This system call asks the operating system to clone whatever process calls it.
  2. As a result of the fork() call, the system replaces the shell process with two new processes. These processes are identical in every respect, except that one is labeled "parent" and the other is labeled "child." The parent process, which is identical to the original shell, then begins to wait for the child process to terminate.
  3. The child process, which is a copy of the original shell, now makes a second system call, called exec(). While fork() clones a process, exec() starts a new process that replaces whatever process called it. In this instance, the child shell exec is the new grep process, and the child shell disappears, replaced by grep.
  4. The grep process terminates, and the parent shell, which was waiting for this event, wakes up and generates a new login prompt.

Process ID and parent process ID

Every process on the system is numbered, starting from 1. This number is called the Process ID (PID). The ancestor of all processes on the system is the process init, which is started at boot time and is automatically given the PID of 1. All other processes on the system are derived from init by the fork and exec procedures, either directly or indirectly. Because every process results from a fork(), every process has a parent process--the process that called the fork() that created it. Because all processes derive ultimately from init with PID 1, tracing the chain of ancestry back from any running process must ultimately lead to init.

Killing a process

If you know a process’s PID, then you can terminate that process by using the kill command. For example, to stop a process with the PID 34, you would type
kill 34

Forking Process - Quiz

Click the Quiz link to take a short multiple-choice quiz on processes.
Forking Process - Quiz
boot: To boot a system means to start it up. Many systems are configured to boot automatically after the power comes on or after a system crash.