7.3.2 Forking and Variables
7.3.2 Forking and Variables
We know forked processes execute the same code. In other words, forked processes share the same code. This also means that forked processes have the same programming environment. However, on fork(), the parent process is cloned. A program’s code (or, the instruction segment) is usually read-only and therefore is not usually copied by the cloned process. Both execute or share the same code. The variables that a process deals with are stored in a separate part of the memory called data segment. A copy of the data segment for the parent process is made for the child process. Therefore, although the child process uses the same variable names, it has a separate copy of each variable.
Let us look at the program that follows and see how the variables are updated by the two processes after a fork().
Program 7.14
#!/usr/bin/perl use strict; my $i = 0; fork (); #Each process increments its copy of $i $i++; print "\$i = $i\n";
Here, the variable name $i is available to both processes after the fork() command is executed. However, there are two separate copies of $i in the two data segments of the two processes. Therefore, each updates its copy of $i and prints the updated value separately. The output of the program is given below.
$i = 1 $i = 1
From what we have seen so far, it is not possible to know which process printed which line of output. But, we will soon know how to distinguish the two processes from each other.
By this time, one should realize that forking is expensive on system resources. Copies have to be made of the data for each process. Depending on how much data is involved and depending on how many processes are spawned or forked, it can become quite resource intensive. So, forking should be done with caution.
