dicroce
dicroce

Reputation: 46770

If the same shared library is loaded by different applications and from different directories, is it shared in memory?

I have been told that in general, Linux will avoid loading multiple copies of the same shared library. My question really is about how robust this mechanism is. If multiple copies of the same library exist in multiple places on your system, will they be shared in memory? Is this any different if you dlopen()'d the library (vs. just linking against it).

Upvotes: 2

Views: 497

Answers (2)

user149341
user149341

Reputation:

If the library exists as multiple files on disk, it is not shared, as the system has no sensible way of determining that they're actually the same.

Upvotes: 1

Dynamic libraries are loaded (either by the dynamic loader ld.so(8) or by dlopen(3), which is often using code from ld.so) using several calls to the mmap(2) syscall.

Generally, the read-only data -and the code- are MAP_SHARED. So the RAM (and the memory mapping enforced by the MMU and the kernel) is shared between all the processes.

Of course, what really matters is the inode which is mmap-ed (or execve-ed). So two file copies of the same shared library won't be shared. (better use symlinks).

You can understand the memory map of process 1234 by reading sequentially /proc/1234/maps. For example, try cat /proc/$$/maps in a terminal. See proc(5) for details about /proc/ pseudo-file system. Try also lsof

Upvotes: 2

Related Questions