Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is fork() copy-on-write a stable exposed behavior that can be used to implement read-only shared memory?

Tags:

linux

fork

The man page on fork() states that it does not copy data pages, it maps them into the child process and puts a copy-on-write flag. Is that behavior:

  • consistent between flavors of Linux?
  • considered an implementation detail and therefore likely to change?

I'm wondering if I can use fork() as a means to get a shared read-only memory block on the cheap. If the memory is physically copied, it would be rather expensive - there's a lot of forking going on, and the data area is big enough - but I'm hoping not...

like image 716
Seva Alekseyev Avatar asked Dec 22 '22 23:12

Seva Alekseyev


1 Answers

Linux running on machines without a MMU (memory management unit) will copy all process memory on fork().

However, those systems are usually very small and embedded and you probably don't have to worry about them.

Many services such as Apache's fork model, use the initialize and fork() method to share initialized data structures.

You should be aware that if you are using languages like Perl and Python that use reference-counted variables, or C++ shared_ptr's, this model will not work. It will not work because as the reference counts are adjusted up and down, the memory becomes unshared and gets copied.

This causes huge amounts of memory usage in Perl daemons like SpamAssassin that attempt to use an initialize and fork model.

like image 91
Zan Lynx Avatar answered Dec 27 '22 08:12

Zan Lynx