I tried to write a small application to familiarize myself with the concept of copy-on-write in user space. I read the answer from MSalters and realized that it would work only if I start with the mmap 'ed file to store my data. Since I need a file-based persistent, I tried to do the same with shared memory. First, I mmap 'ed and initialized shm fd, then I displayed the second copy using MAP_PRIVATE and read it again. However, a simple reading from it makes the kernel copy all of this, taking up significantly more time and consuming twice as much memory. Why does this not do COW?
Here is the program I came up with to illustrate the behavior:
#include <stdio.h>
I compiled it with g++ -O3 -mtune=native -march=native -o shm-min shm-min.cpp -lrt .
The created array contains 4 GB of integer values. Right before the program ends, however, 8 GB of shared memory is allocated, and in /proc/<pid>/smaps you can see that in fact it completely copied during the read-only operation. I have no idea why this is. Is this a kernel bug? Or am I missing something?
Thanks so much for any ideas. Lars
Edit Here is the relevant content /proc/<pid>/smaps on Ubuntu 14.04 (3.13.0-24):
7f3b9b4ae000-7f3c9b4ae000 r--p 00000000 00:14 168154 /run/shm/cowtest (deleted) Size: 4194304 kB Rss: 4194304 kB Pss: 2097152 kB Shared_Clean: 0 kB Shared_Dirty: 4194304 kB Private_Clean: 0 kB Private_Dirty: 0 kB Referenced: 4194304 kB Anonymous: 0 kB AnonHugePages: 0 kB Swap: 0 kB KernelPageSize: 4 kB MMUPageSize: 4 kB Locked: 0 kB VmFlags: rd mr mw me sd 7f3c9b4ae000-7f3d9b4ae000 rw-s 00000000 00:14 168154 /run/shm/cowtest (deleted) Size: 4194304 kB Rss: 4194304 kB Pss: 2097152 kB Shared_Clean: 0 kB Shared_Dirty: 4194304 kB Private_Clean: 0 kB Private_Dirty: 0 kB Referenced: 4194304 kB Anonymous: 0 kB AnonHugePages: 0 kB Swap: 0 kB KernelPageSize: 4 kB MMUPageSize: 4 kB Locked: 0 kB VmFlags: rd wr sh mr mw me ms sd
c ++ memory-management linux shared-memory memory
lekv
source share