Understanding Copy-on-Write in the Context of fork()
When a process calls fork(), the operating system creates a new process (child) by duplicating the memory space of the parent. However, to optimize performance, modern operating systems employ a technique known as Copy-on-Write (COW).
What is Copy-on-Write?
Copy-on-Write delays the actual copying of memory pages until one of the processes (parent or child) tries to modify a shared page. Initially, both processes share the same physical memory pages marked as read-only. When a process attempts to write to a shared page, a page fault is triggered. The OS then:
Allocates a new page,
Copies the contents of the original page to the new one,
Updates the process’s page table to point to the new writable page.
This way, memory is conserved, and copying overhead is avoided unless absolutely necessary.
Code Under Consideration
if (fork() == 0) {
a = a + 5;
printf("%d, %p\n", a, &a);
} else {
a = a - 5;
printf("%d, %p\n", a, &a);
}
Analysis
Let’s break it down with Copy-on-Write in mind:
Before the fork(), there’s a variable a (assume it’s a global or stack variable).
After fork(), both parent and child share the same virtual address space, including variable a, using COW.
When either process tries to write to a, the OS creates a private copy for that process (due to COW), but the virtual address &a remains the same in both processes.
Therefore:
Both the parent and child will print different values of a (one does a+5, the other a-5),
But both will print the same address for &a.
So the correct option is:
(C) Both processes print different values, but the same address.
Resource
Further reading: Copy-on-Write in Operating System - Studytonight