Shared memory pages and fork
kernel, linux
Solution
The kernel knows which memory pages were allocated using shared memory operations. When a child is forked, those pages are not marked Copy-on-Write, so they will remain shared among all the processes.
This is recorded in the `vm_area_struct` data structure, in the `vm_flags` member. One of the flags is `VM_SHARED`. mm/memory.c contains the following function that determines if a page should be converted to COW
static inline int is_cow_mapping(vm_flags_t flags)
{
return (flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
}
If you want to see more about how this flag is set and used, go to Linux Cross Reference and search for VM_SHARED.
Problem
If the parent is sharing some pages with another process and we fork the parent. From what I know the child copies the page tables and we set the pages as read-only and do Copy-On-Write. But this will create a copy of the shared memory page if we write to it which is wrong. How does the Linux kernel avoid this?