3

I would like to write a small program that demonstrates whether the operating system is using copy-on-write after a call to fork(). The problem is that copy-on-write is mostly transparent to affected processes.

For a given variable, virtual memory addresses accessed with the & operator appear identical for forked processes even when those processes store different values in that variable. Is there a way to determine if variables in separate processes are stored at the same physical address? Is there a way to determine if they are not?

Praxeolitic
  • 22,455
  • 16
  • 75
  • 126

3 Answers3

5

In general, in the sense of being portable to all POSIX conforming or POSIX-like systems, no, there is no way to observe COW, especially not at the individual page level (you might be able to observe it on a broader level just by "available" memory if the system provides such a figure). But on Linux you can observe it via /proc/[pid]/pagemap for the potentially-sharing processes. /proc/kpagecount and /proc/kpageflags may also contain relevant information but you need root to access them. See:

https://www.kernel.org/doc/Documentation/vm/pagemap.txt

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
1

I'm speculating here, but I'd expect that within the process it would not be possible. As you say we effectively have perfect copy of the address space. However you do have some uniqueness, for example the process id, and so could write a process-unique value to a chosen address and then either write the value out to a file or use inter-process communication (eg. a pipe) to allow the processes to compare their values and hence confirm that they are now different.

djna
  • 54,992
  • 14
  • 74
  • 117
1

POSIX doesn't specify copy-on-write behavior, so there's no standard way to detect it because a system might not even use COW.

Maybe you could fiddle with your virtual memory ulimit, locking it down to some small number such that modifying a page would put you over and get you a signal. This would be very sensitive to system details, if you could make it work at all.

If you want a Linux-specific solution, and you're running a 2.6.34 or later kernel, this Q&A should help you. It's not trivial.

Community
  • 1
  • 1
rob mayoff
  • 375,296
  • 67
  • 796
  • 848