Page 421 - DCAP103_Principle of operating system
P. 421
Principles of Operating Systems
Notes now allocate memory for the child’s data and stack segments, and to make exact copies of the
parents’ segments, since the semantics of fork say that no memory is shared between parent
and child. The text segment may either be copied or shared since it is read only. At this point,
the child is ready to run.
However, copying memory is expensive, so all modern Linux systems cheat. They give the
child its own page tables, but have them point to the parent’s pages, only marked read only.
Whenever the child tries to write on a page, it gets a faulty protection. The kernel sees this
and then allocates a new copy of the page to the child and marks it read/write. In this way,
only pages that are actually written have to be copied. This mechanism is called copy on
write. It has the additional benefit of not requiring two copies of the program in memory,
thus saving in RAM. After the child process starts running, the code running there (a copy
of the shell) does an exec system call giving the command name as a parameter. The kernel
now finds and verifies the executable file, copies the arguments and environment strings
to the kernel, and releases the old address space and its page tables. Now the new address
space must be created and filled in. If the system supports mapped files, as Linux and other
UNIX-based systems do, the new page tables are set up to indicate that no pages are in memory,
except perhaps one stack page, but that the address space is backed by the executable file on
disk. When the new process starts running, it will immediately get a page fault, which will
cause the first page of code to be paged in from the executable file. In this way, nothing has
to be loaded in advance, so programs can start quickly and fault in just those pages they need
and no more. Finally, the arguments and environment strings are copied to the new stack, the
signals are reset, and the registers are initialized to all zeros. At this point, the new command can
start running. Figure 14.8 illustrates the steps described above through the following example:
A user types a command, ls on the terminal, the shell creates a new process by forking off a
clone of itself. The new shell then calls exec to overlay its memory with the contents of the
executable file ls.
Figure 14.8: The Steps in Executing the Command ls Typed to the Shell
14.2.4 Threads in Linux
We discussed threads in a general way. Here, we will focus on kernel threads in Linux,
particularly focusing on the differences in the Linux thread models and other UNIX systems.
414 LOVELY PROFESSIONAL UNIVERSITY